diffcore-rename: fall back to -C when -C -C busts the rename limit
[git.git] / builtin / log.c
blob707fd5706c37290bd65fcdf1f482202c54205881
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 "color.h"
9 #include "commit.h"
10 #include "diff.h"
11 #include "revision.h"
12 #include "log-tree.h"
13 #include "builtin.h"
14 #include "tag.h"
15 #include "reflog-walk.h"
16 #include "patch-ids.h"
17 #include "run-command.h"
18 #include "shortlog.h"
19 #include "remote.h"
20 #include "string-list.h"
21 #include "parse-options.h"
23 /* Set a default date-time format for git log ("log.date" config variable) */
24 static const char *default_date_mode = NULL;
26 static int default_show_root = 1;
27 static int decoration_style;
28 static const char *fmt_patch_subject_prefix = "PATCH";
29 static const char *fmt_pretty;
31 static const char * const builtin_log_usage =
32 "git log [<options>] [<since>..<until>] [[--] <path>...]\n"
33 " or: git show [options] <object>...";
35 static int parse_decoration_style(const char *var, const char *value)
37 switch (git_config_maybe_bool(var, value)) {
38 case 1:
39 return DECORATE_SHORT_REFS;
40 case 0:
41 return 0;
42 default:
43 break;
45 if (!strcmp(value, "full"))
46 return DECORATE_FULL_REFS;
47 else if (!strcmp(value, "short"))
48 return DECORATE_SHORT_REFS;
49 return -1;
52 static void cmd_log_init(int argc, const char **argv, const char *prefix,
53 struct rev_info *rev, struct setup_revision_opt *opt)
55 int i;
56 int decoration_given = 0;
57 struct userformat_want w;
59 rev->abbrev = DEFAULT_ABBREV;
60 rev->commit_format = CMIT_FMT_DEFAULT;
61 if (fmt_pretty)
62 get_commit_format(fmt_pretty, rev);
63 rev->verbose_header = 1;
64 DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
65 rev->show_root_diff = default_show_root;
66 rev->subject_prefix = fmt_patch_subject_prefix;
67 DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
69 if (default_date_mode)
70 rev->date_mode = parse_date_format(default_date_mode);
73 * Check for -h before setup_revisions(), or "git log -h" will
74 * fail when run without a git directory.
76 if (argc == 2 && !strcmp(argv[1], "-h"))
77 usage(builtin_log_usage);
78 argc = setup_revisions(argc, argv, rev, opt);
80 memset(&w, 0, sizeof(w));
81 userformat_find_requirements(NULL, &w);
83 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
84 rev->show_notes = 1;
85 if (rev->show_notes)
86 init_display_notes(&rev->notes_opt);
88 if (rev->diffopt.pickaxe || rev->diffopt.filter)
89 rev->always_show_header = 0;
90 if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
91 rev->always_show_header = 0;
92 if (rev->diffopt.pathspec.nr != 1)
93 usage("git logs can only follow renames on one pathname at a time");
95 for (i = 1; i < argc; i++) {
96 const char *arg = argv[i];
97 if (!strcmp(arg, "--decorate")) {
98 decoration_style = DECORATE_SHORT_REFS;
99 decoration_given = 1;
100 } else if (!prefixcmp(arg, "--decorate=")) {
101 const char *v = skip_prefix(arg, "--decorate=");
102 decoration_style = parse_decoration_style(arg, v);
103 if (decoration_style < 0)
104 die("invalid --decorate option: %s", arg);
105 decoration_given = 1;
106 } else if (!strcmp(arg, "--no-decorate")) {
107 decoration_style = 0;
108 } else if (!strcmp(arg, "--source")) {
109 rev->show_source = 1;
110 } else if (!strcmp(arg, "-h")) {
111 usage(builtin_log_usage);
112 } else
113 die("unrecognized argument: %s", arg);
117 * defeat log.decorate configuration interacting with --pretty=raw
118 * from the command line.
120 if (!decoration_given && rev->pretty_given
121 && rev->commit_format == CMIT_FMT_RAW)
122 decoration_style = 0;
124 if (decoration_style) {
125 rev->show_decorations = 1;
126 load_ref_decorations(decoration_style);
128 setup_pager();
132 * This gives a rough estimate for how many commits we
133 * will print out in the list.
135 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
137 int n = 0;
139 while (list) {
140 struct commit *commit = list->item;
141 unsigned int flags = commit->object.flags;
142 list = list->next;
143 if (!(flags & (TREESAME | UNINTERESTING)))
144 n++;
146 return n;
149 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
151 if (rev->shown_one) {
152 rev->shown_one = 0;
153 if (rev->commit_format != CMIT_FMT_ONELINE)
154 putchar(rev->diffopt.line_termination);
156 printf("Final output: %d %s\n", nr, stage);
159 static struct itimerval early_output_timer;
161 static void log_show_early(struct rev_info *revs, struct commit_list *list)
163 int i = revs->early_output;
164 int show_header = 1;
166 sort_in_topological_order(&list, revs->lifo);
167 while (list && i) {
168 struct commit *commit = list->item;
169 switch (simplify_commit(revs, commit)) {
170 case commit_show:
171 if (show_header) {
172 int n = estimate_commit_count(revs, list);
173 show_early_header(revs, "incomplete", n);
174 show_header = 0;
176 log_tree_commit(revs, commit);
177 i--;
178 break;
179 case commit_ignore:
180 break;
181 case commit_error:
182 return;
184 list = list->next;
187 /* Did we already get enough commits for the early output? */
188 if (!i)
189 return;
192 * ..if no, then repeat it twice a second until we
193 * do.
195 * NOTE! We don't use "it_interval", because if the
196 * reader isn't listening, we want our output to be
197 * throttled by the writing, and not have the timer
198 * trigger every second even if we're blocked on a
199 * reader!
201 early_output_timer.it_value.tv_sec = 0;
202 early_output_timer.it_value.tv_usec = 500000;
203 setitimer(ITIMER_REAL, &early_output_timer, NULL);
206 static void early_output(int signal)
208 show_early_output = log_show_early;
211 static void setup_early_output(struct rev_info *rev)
213 struct sigaction sa;
216 * Set up the signal handler, minimally intrusively:
217 * we only set a single volatile integer word (not
218 * using sigatomic_t - trying to avoid unnecessary
219 * system dependencies and headers), and using
220 * SA_RESTART.
222 memset(&sa, 0, sizeof(sa));
223 sa.sa_handler = early_output;
224 sigemptyset(&sa.sa_mask);
225 sa.sa_flags = SA_RESTART;
226 sigaction(SIGALRM, &sa, NULL);
229 * If we can get the whole output in less than a
230 * tenth of a second, don't even bother doing the
231 * early-output thing..
233 * This is a one-time-only trigger.
235 early_output_timer.it_value.tv_sec = 0;
236 early_output_timer.it_value.tv_usec = 100000;
237 setitimer(ITIMER_REAL, &early_output_timer, NULL);
240 static void finish_early_output(struct rev_info *rev)
242 int n = estimate_commit_count(rev, rev->commits);
243 signal(SIGALRM, SIG_IGN);
244 show_early_header(rev, "done", n);
247 static int cmd_log_walk(struct rev_info *rev)
249 struct commit *commit;
250 int saved_nrl = 0;
251 int saved_dcctc = 0;
253 if (rev->early_output)
254 setup_early_output(rev);
256 if (prepare_revision_walk(rev))
257 die("revision walk setup failed");
259 if (rev->early_output)
260 finish_early_output(rev);
263 * For --check and --exit-code, the exit code is based on CHECK_FAILED
264 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
265 * retain that state information if replacing rev->diffopt in this loop
267 while ((commit = get_revision(rev)) != NULL) {
268 if (!log_tree_commit(rev, commit) &&
269 rev->max_count >= 0)
271 * We decremented max_count in get_revision,
272 * but we didn't actually show the commit.
274 rev->max_count++;
275 if (!rev->reflog_info) {
276 /* we allow cycles in reflog ancestry */
277 free(commit->buffer);
278 commit->buffer = NULL;
280 free_commit_list(commit->parents);
281 commit->parents = NULL;
282 if (saved_nrl < rev->diffopt.needed_rename_limit)
283 saved_nrl = rev->diffopt.needed_rename_limit;
284 if (rev->diffopt.degraded_cc_to_c)
285 saved_dcctc = 1;
287 rev->diffopt.degraded_cc_to_c = saved_dcctc;
288 rev->diffopt.needed_rename_limit = saved_nrl;
290 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
291 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
292 return 02;
294 return diff_result_code(&rev->diffopt, 0);
297 static int git_log_config(const char *var, const char *value, void *cb)
299 if (!strcmp(var, "format.pretty"))
300 return git_config_string(&fmt_pretty, var, value);
301 if (!strcmp(var, "format.subjectprefix"))
302 return git_config_string(&fmt_patch_subject_prefix, var, value);
303 if (!strcmp(var, "log.date"))
304 return git_config_string(&default_date_mode, var, value);
305 if (!strcmp(var, "log.decorate")) {
306 decoration_style = parse_decoration_style(var, value);
307 if (decoration_style < 0)
308 decoration_style = 0; /* maybe warn? */
309 return 0;
311 if (!strcmp(var, "log.showroot")) {
312 default_show_root = git_config_bool(var, value);
313 return 0;
315 if (!prefixcmp(var, "color.decorate."))
316 return parse_decorate_color_config(var, 15, value);
318 return git_diff_ui_config(var, value, cb);
321 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
323 struct rev_info rev;
324 struct setup_revision_opt opt;
326 git_config(git_log_config, NULL);
328 if (diff_use_color_default == -1)
329 diff_use_color_default = git_use_color_default;
331 init_revisions(&rev, prefix);
332 rev.diff = 1;
333 rev.simplify_history = 0;
334 memset(&opt, 0, sizeof(opt));
335 opt.def = "HEAD";
336 cmd_log_init(argc, argv, prefix, &rev, &opt);
337 if (!rev.diffopt.output_format)
338 rev.diffopt.output_format = DIFF_FORMAT_RAW;
339 return cmd_log_walk(&rev);
342 static void show_tagger(char *buf, int len, struct rev_info *rev)
344 struct strbuf out = STRBUF_INIT;
346 pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
347 get_log_output_encoding());
348 printf("%s", out.buf);
349 strbuf_release(&out);
352 static int show_object(const unsigned char *sha1, int show_tag_object,
353 struct rev_info *rev)
355 unsigned long size;
356 enum object_type type;
357 char *buf = read_sha1_file(sha1, &type, &size);
358 int offset = 0;
360 if (!buf)
361 return error("Could not read object %s", sha1_to_hex(sha1));
363 if (show_tag_object)
364 while (offset < size && buf[offset] != '\n') {
365 int new_offset = offset + 1;
366 while (new_offset < size && buf[new_offset++] != '\n')
367 ; /* do nothing */
368 if (!prefixcmp(buf + offset, "tagger "))
369 show_tagger(buf + offset + 7,
370 new_offset - offset - 7, rev);
371 offset = new_offset;
374 if (offset < size)
375 fwrite(buf + offset, size - offset, 1, stdout);
376 free(buf);
377 return 0;
380 static int show_tree_object(const unsigned char *sha1,
381 const char *base, int baselen,
382 const char *pathname, unsigned mode, int stage, void *context)
384 printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
385 return 0;
388 static void show_rev_tweak_rev(struct rev_info *rev, struct setup_revision_opt *opt)
390 if (rev->ignore_merges) {
391 /* There was no "-m" on the command line */
392 rev->ignore_merges = 0;
393 if (!rev->first_parent_only && !rev->combine_merges) {
394 /* No "--first-parent", "-c", nor "--cc" */
395 rev->combine_merges = 1;
396 rev->dense_combined_merges = 1;
399 if (!rev->diffopt.output_format)
400 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
403 int cmd_show(int argc, const char **argv, const char *prefix)
405 struct rev_info rev;
406 struct object_array_entry *objects;
407 struct setup_revision_opt opt;
408 int i, count, ret = 0;
410 git_config(git_log_config, NULL);
412 if (diff_use_color_default == -1)
413 diff_use_color_default = git_use_color_default;
415 init_revisions(&rev, prefix);
416 rev.diff = 1;
417 rev.always_show_header = 1;
418 rev.no_walk = 1;
419 memset(&opt, 0, sizeof(opt));
420 opt.def = "HEAD";
421 opt.tweak = show_rev_tweak_rev;
422 cmd_log_init(argc, argv, prefix, &rev, &opt);
424 count = rev.pending.nr;
425 objects = rev.pending.objects;
426 for (i = 0; i < count && !ret; i++) {
427 struct object *o = objects[i].item;
428 const char *name = objects[i].name;
429 switch (o->type) {
430 case OBJ_BLOB:
431 ret = show_object(o->sha1, 0, NULL);
432 break;
433 case OBJ_TAG: {
434 struct tag *t = (struct tag *)o;
436 if (rev.shown_one)
437 putchar('\n');
438 printf("%stag %s%s\n",
439 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
440 t->tag,
441 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
442 ret = show_object(o->sha1, 1, &rev);
443 rev.shown_one = 1;
444 if (ret)
445 break;
446 o = parse_object(t->tagged->sha1);
447 if (!o)
448 ret = error("Could not read object %s",
449 sha1_to_hex(t->tagged->sha1));
450 objects[i].item = o;
451 i--;
452 break;
454 case OBJ_TREE:
455 if (rev.shown_one)
456 putchar('\n');
457 printf("%stree %s%s\n\n",
458 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
459 name,
460 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
461 read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
462 show_tree_object, NULL);
463 rev.shown_one = 1;
464 break;
465 case OBJ_COMMIT:
466 rev.pending.nr = rev.pending.alloc = 0;
467 rev.pending.objects = NULL;
468 add_object_array(o, name, &rev.pending);
469 ret = cmd_log_walk(&rev);
470 break;
471 default:
472 ret = error("Unknown type: %d", o->type);
475 free(objects);
476 return ret;
480 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
482 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
484 struct rev_info rev;
485 struct setup_revision_opt opt;
487 git_config(git_log_config, NULL);
489 if (diff_use_color_default == -1)
490 diff_use_color_default = git_use_color_default;
492 init_revisions(&rev, prefix);
493 init_reflog_walk(&rev.reflog_info);
494 rev.abbrev_commit = 1;
495 rev.verbose_header = 1;
496 memset(&opt, 0, sizeof(opt));
497 opt.def = "HEAD";
498 cmd_log_init(argc, argv, prefix, &rev, &opt);
501 * This means that we override whatever commit format the user gave
502 * on the cmd line. Sad, but cmd_log_init() currently doesn't
503 * allow us to set a different default.
505 rev.commit_format = CMIT_FMT_ONELINE;
506 rev.use_terminator = 1;
507 rev.always_show_header = 1;
509 return cmd_log_walk(&rev);
512 int cmd_log(int argc, const char **argv, const char *prefix)
514 struct rev_info rev;
515 struct setup_revision_opt opt;
517 git_config(git_log_config, NULL);
519 if (diff_use_color_default == -1)
520 diff_use_color_default = git_use_color_default;
522 init_revisions(&rev, prefix);
523 rev.always_show_header = 1;
524 memset(&opt, 0, sizeof(opt));
525 opt.def = "HEAD";
526 cmd_log_init(argc, argv, prefix, &rev, &opt);
527 return cmd_log_walk(&rev);
530 /* format-patch */
532 static const char *fmt_patch_suffix = ".patch";
533 static int numbered = 0;
534 static int auto_number = 1;
536 static char *default_attach = NULL;
538 static struct string_list extra_hdr;
539 static struct string_list extra_to;
540 static struct string_list extra_cc;
542 static void add_header(const char *value)
544 struct string_list_item *item;
545 int len = strlen(value);
546 while (len && value[len - 1] == '\n')
547 len--;
549 if (!strncasecmp(value, "to: ", 4)) {
550 item = string_list_append(&extra_to, value + 4);
551 len -= 4;
552 } else if (!strncasecmp(value, "cc: ", 4)) {
553 item = string_list_append(&extra_cc, value + 4);
554 len -= 4;
555 } else {
556 item = string_list_append(&extra_hdr, value);
559 item->string[len] = '\0';
562 #define THREAD_SHALLOW 1
563 #define THREAD_DEEP 2
564 static int thread;
565 static int do_signoff;
566 static const char *signature = git_version_string;
568 static int git_format_config(const char *var, const char *value, void *cb)
570 if (!strcmp(var, "format.headers")) {
571 if (!value)
572 die("format.headers without value");
573 add_header(value);
574 return 0;
576 if (!strcmp(var, "format.suffix"))
577 return git_config_string(&fmt_patch_suffix, var, value);
578 if (!strcmp(var, "format.to")) {
579 if (!value)
580 return config_error_nonbool(var);
581 string_list_append(&extra_to, value);
582 return 0;
584 if (!strcmp(var, "format.cc")) {
585 if (!value)
586 return config_error_nonbool(var);
587 string_list_append(&extra_cc, value);
588 return 0;
590 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
591 return 0;
593 if (!strcmp(var, "format.numbered")) {
594 if (value && !strcasecmp(value, "auto")) {
595 auto_number = 1;
596 return 0;
598 numbered = git_config_bool(var, value);
599 auto_number = auto_number && numbered;
600 return 0;
602 if (!strcmp(var, "format.attach")) {
603 if (value && *value)
604 default_attach = xstrdup(value);
605 else
606 default_attach = xstrdup(git_version_string);
607 return 0;
609 if (!strcmp(var, "format.thread")) {
610 if (value && !strcasecmp(value, "deep")) {
611 thread = THREAD_DEEP;
612 return 0;
614 if (value && !strcasecmp(value, "shallow")) {
615 thread = THREAD_SHALLOW;
616 return 0;
618 thread = git_config_bool(var, value) && THREAD_SHALLOW;
619 return 0;
621 if (!strcmp(var, "format.signoff")) {
622 do_signoff = git_config_bool(var, value);
623 return 0;
625 if (!strcmp(var, "format.signature"))
626 return git_config_string(&signature, var, value);
628 return git_log_config(var, value, cb);
631 static FILE *realstdout = NULL;
632 static const char *output_directory = NULL;
633 static int outdir_offset;
635 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
637 struct strbuf filename = STRBUF_INIT;
638 int suffix_len = strlen(fmt_patch_suffix) + 1;
640 if (output_directory) {
641 strbuf_addstr(&filename, output_directory);
642 if (filename.len >=
643 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
644 return error("name of output directory is too long");
645 if (filename.buf[filename.len - 1] != '/')
646 strbuf_addch(&filename, '/');
649 get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
651 if (!DIFF_OPT_TST(&rev->diffopt, QUICK))
652 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
654 if (freopen(filename.buf, "w", stdout) == NULL)
655 return error("Cannot open patch file %s", filename.buf);
657 strbuf_release(&filename);
658 return 0;
661 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
663 struct rev_info check_rev;
664 struct commit *commit;
665 struct object *o1, *o2;
666 unsigned flags1, flags2;
668 if (rev->pending.nr != 2)
669 die("Need exactly one range.");
671 o1 = rev->pending.objects[0].item;
672 flags1 = o1->flags;
673 o2 = rev->pending.objects[1].item;
674 flags2 = o2->flags;
676 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
677 die("Not a range.");
679 init_patch_ids(ids);
681 /* given a range a..b get all patch ids for b..a */
682 init_revisions(&check_rev, prefix);
683 o1->flags ^= UNINTERESTING;
684 o2->flags ^= UNINTERESTING;
685 add_pending_object(&check_rev, o1, "o1");
686 add_pending_object(&check_rev, o2, "o2");
687 if (prepare_revision_walk(&check_rev))
688 die("revision walk setup failed");
690 while ((commit = get_revision(&check_rev)) != NULL) {
691 /* ignore merges */
692 if (commit->parents && commit->parents->next)
693 continue;
695 add_commit_patch_id(commit, ids);
698 /* reset for next revision walk */
699 clear_commit_marks((struct commit *)o1,
700 SEEN | UNINTERESTING | SHOWN | ADDED);
701 clear_commit_marks((struct commit *)o2,
702 SEEN | UNINTERESTING | SHOWN | ADDED);
703 o1->flags = flags1;
704 o2->flags = flags2;
707 static void gen_message_id(struct rev_info *info, char *base)
709 const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
710 const char *email_start = strrchr(committer, '<');
711 const char *email_end = strrchr(committer, '>');
712 struct strbuf buf = STRBUF_INIT;
713 if (!email_start || !email_end || email_start > email_end - 1)
714 die("Could not extract email from committer identity.");
715 strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
716 (unsigned long) time(NULL),
717 (int)(email_end - email_start - 1), email_start + 1);
718 info->message_id = strbuf_detach(&buf, NULL);
721 static void print_signature(void)
723 if (signature && *signature)
724 printf("-- \n%s\n\n", signature);
727 static void make_cover_letter(struct rev_info *rev, int use_stdout,
728 int numbered, int numbered_files,
729 struct commit *origin,
730 int nr, struct commit **list, struct commit *head)
732 const char *committer;
733 const char *subject_start = NULL;
734 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
735 const char *msg;
736 const char *extra_headers = rev->extra_headers;
737 struct shortlog log;
738 struct strbuf sb = STRBUF_INIT;
739 int i;
740 const char *encoding = "UTF-8";
741 struct diff_options opts;
742 int need_8bit_cte = 0;
743 struct commit *commit = NULL;
745 if (rev->commit_format != CMIT_FMT_EMAIL)
746 die("Cover letter needs email format");
748 committer = git_committer_info(0);
750 if (!numbered_files) {
752 * We fake a commit for the cover letter so we get the filename
753 * desired.
755 commit = xcalloc(1, sizeof(*commit));
756 commit->buffer = xmalloc(400);
757 snprintf(commit->buffer, 400,
758 "tree 0000000000000000000000000000000000000000\n"
759 "parent %s\n"
760 "author %s\n"
761 "committer %s\n\n"
762 "cover letter\n",
763 sha1_to_hex(head->object.sha1), committer, committer);
766 if (!use_stdout && reopen_stdout(commit, rev))
767 return;
769 if (commit) {
771 free(commit->buffer);
772 free(commit);
775 log_write_email_headers(rev, head, &subject_start, &extra_headers,
776 &need_8bit_cte);
778 for (i = 0; !need_8bit_cte && i < nr; i++)
779 if (has_non_ascii(list[i]->buffer))
780 need_8bit_cte = 1;
782 msg = body;
783 pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
784 encoding);
785 pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
786 encoding, need_8bit_cte);
787 pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
788 printf("%s\n", sb.buf);
790 strbuf_release(&sb);
792 shortlog_init(&log);
793 log.wrap_lines = 1;
794 log.wrap = 72;
795 log.in1 = 2;
796 log.in2 = 4;
797 for (i = 0; i < nr; i++)
798 shortlog_add_commit(&log, list[i]);
800 shortlog_output(&log);
803 * We can only do diffstat with a unique reference point
805 if (!origin)
806 return;
808 memcpy(&opts, &rev->diffopt, sizeof(opts));
809 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
811 diff_setup_done(&opts);
813 diff_tree_sha1(origin->tree->object.sha1,
814 head->tree->object.sha1,
815 "", &opts);
816 diffcore_std(&opts);
817 diff_flush(&opts);
819 printf("\n");
820 print_signature();
823 static const char *clean_message_id(const char *msg_id)
825 char ch;
826 const char *a, *z, *m;
828 m = msg_id;
829 while ((ch = *m) && (isspace(ch) || (ch == '<')))
830 m++;
831 a = m;
832 z = NULL;
833 while ((ch = *m)) {
834 if (!isspace(ch) && (ch != '>'))
835 z = m;
836 m++;
838 if (!z)
839 die("insane in-reply-to: %s", msg_id);
840 if (++z == m)
841 return a;
842 return xmemdupz(a, z - a);
845 static const char *set_outdir(const char *prefix, const char *output_directory)
847 if (output_directory && is_absolute_path(output_directory))
848 return output_directory;
850 if (!prefix || !*prefix) {
851 if (output_directory)
852 return output_directory;
853 /* The user did not explicitly ask for "./" */
854 outdir_offset = 2;
855 return "./";
858 outdir_offset = strlen(prefix);
859 if (!output_directory)
860 return prefix;
862 return xstrdup(prefix_filename(prefix, outdir_offset,
863 output_directory));
866 static const char * const builtin_format_patch_usage[] = {
867 "git format-patch [options] [<since> | <revision range>]",
868 NULL
871 static int keep_subject = 0;
873 static int keep_callback(const struct option *opt, const char *arg, int unset)
875 ((struct rev_info *)opt->value)->total = -1;
876 keep_subject = 1;
877 return 0;
880 static int subject_prefix = 0;
882 static int subject_prefix_callback(const struct option *opt, const char *arg,
883 int unset)
885 subject_prefix = 1;
886 ((struct rev_info *)opt->value)->subject_prefix = arg;
887 return 0;
890 static int numbered_cmdline_opt = 0;
892 static int numbered_callback(const struct option *opt, const char *arg,
893 int unset)
895 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
896 if (unset)
897 auto_number = 0;
898 return 0;
901 static int no_numbered_callback(const struct option *opt, const char *arg,
902 int unset)
904 return numbered_callback(opt, arg, 1);
907 static int output_directory_callback(const struct option *opt, const char *arg,
908 int unset)
910 const char **dir = (const char **)opt->value;
911 if (*dir)
912 die("Two output directories?");
913 *dir = arg;
914 return 0;
917 static int thread_callback(const struct option *opt, const char *arg, int unset)
919 int *thread = (int *)opt->value;
920 if (unset)
921 *thread = 0;
922 else if (!arg || !strcmp(arg, "shallow"))
923 *thread = THREAD_SHALLOW;
924 else if (!strcmp(arg, "deep"))
925 *thread = THREAD_DEEP;
926 else
927 return 1;
928 return 0;
931 static int attach_callback(const struct option *opt, const char *arg, int unset)
933 struct rev_info *rev = (struct rev_info *)opt->value;
934 if (unset)
935 rev->mime_boundary = NULL;
936 else if (arg)
937 rev->mime_boundary = arg;
938 else
939 rev->mime_boundary = git_version_string;
940 rev->no_inline = unset ? 0 : 1;
941 return 0;
944 static int inline_callback(const struct option *opt, const char *arg, int unset)
946 struct rev_info *rev = (struct rev_info *)opt->value;
947 if (unset)
948 rev->mime_boundary = NULL;
949 else if (arg)
950 rev->mime_boundary = arg;
951 else
952 rev->mime_boundary = git_version_string;
953 rev->no_inline = 0;
954 return 0;
957 static int header_callback(const struct option *opt, const char *arg, int unset)
959 if (unset) {
960 string_list_clear(&extra_hdr, 0);
961 string_list_clear(&extra_to, 0);
962 string_list_clear(&extra_cc, 0);
963 } else {
964 add_header(arg);
966 return 0;
969 static int to_callback(const struct option *opt, const char *arg, int unset)
971 if (unset)
972 string_list_clear(&extra_to, 0);
973 else
974 string_list_append(&extra_to, arg);
975 return 0;
978 static int cc_callback(const struct option *opt, const char *arg, int unset)
980 if (unset)
981 string_list_clear(&extra_cc, 0);
982 else
983 string_list_append(&extra_cc, arg);
984 return 0;
987 int cmd_format_patch(int argc, const char **argv, const char *prefix)
989 struct commit *commit;
990 struct commit **list = NULL;
991 struct rev_info rev;
992 struct setup_revision_opt s_r_opt;
993 int nr = 0, total, i;
994 int use_stdout = 0;
995 int start_number = -1;
996 int numbered_files = 0; /* _just_ numbers */
997 int ignore_if_in_upstream = 0;
998 int cover_letter = 0;
999 int boundary_count = 0;
1000 int no_binary_diff = 0;
1001 struct commit *origin = NULL, *head = NULL;
1002 const char *in_reply_to = NULL;
1003 struct patch_ids ids;
1004 char *add_signoff = NULL;
1005 struct strbuf buf = STRBUF_INIT;
1006 int use_patch_format = 0;
1007 const struct option builtin_format_patch_options[] = {
1008 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
1009 "use [PATCH n/m] even with a single patch",
1010 PARSE_OPT_NOARG, numbered_callback },
1011 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
1012 "use [PATCH] even with multiple patches",
1013 PARSE_OPT_NOARG, no_numbered_callback },
1014 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
1015 OPT_BOOLEAN(0, "stdout", &use_stdout,
1016 "print patches to standard out"),
1017 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
1018 "generate a cover letter"),
1019 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
1020 "use simple number sequence for output file names"),
1021 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
1022 "use <sfx> instead of '.patch'"),
1023 OPT_INTEGER(0, "start-number", &start_number,
1024 "start numbering patches at <n> instead of 1"),
1025 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
1026 "Use [<prefix>] instead of [PATCH]",
1027 PARSE_OPT_NONEG, subject_prefix_callback },
1028 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
1029 "dir", "store resulting files in <dir>",
1030 PARSE_OPT_NONEG, output_directory_callback },
1031 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
1032 "don't strip/add [PATCH]",
1033 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
1034 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
1035 "don't output binary diffs"),
1036 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1037 "don't include a patch matching a commit upstream"),
1038 { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
1039 "show patch format instead of default (patch + stat)",
1040 PARSE_OPT_NONEG | PARSE_OPT_NOARG },
1041 OPT_GROUP("Messaging"),
1042 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
1043 "add email header", 0, header_callback },
1044 { OPTION_CALLBACK, 0, "to", NULL, "email", "add To: header",
1045 0, to_callback },
1046 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
1047 0, cc_callback },
1048 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
1049 "make first mail a reply to <message-id>"),
1050 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
1051 "attach the patch", PARSE_OPT_OPTARG,
1052 attach_callback },
1053 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
1054 "inline the patch",
1055 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1056 inline_callback },
1057 { OPTION_CALLBACK, 0, "thread", &thread, "style",
1058 "enable message threading, styles: shallow, deep",
1059 PARSE_OPT_OPTARG, thread_callback },
1060 OPT_STRING(0, "signature", &signature, "signature",
1061 "add a signature"),
1062 OPT_END()
1065 extra_hdr.strdup_strings = 1;
1066 extra_to.strdup_strings = 1;
1067 extra_cc.strdup_strings = 1;
1068 git_config(git_format_config, NULL);
1069 init_revisions(&rev, prefix);
1070 rev.commit_format = CMIT_FMT_EMAIL;
1071 rev.verbose_header = 1;
1072 rev.diff = 1;
1073 rev.no_merges = 1;
1074 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1075 rev.subject_prefix = fmt_patch_subject_prefix;
1076 memset(&s_r_opt, 0, sizeof(s_r_opt));
1077 s_r_opt.def = "HEAD";
1079 if (default_attach) {
1080 rev.mime_boundary = default_attach;
1081 rev.no_inline = 1;
1085 * Parse the arguments before setup_revisions(), or something
1086 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1087 * possibly a valid SHA1.
1089 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1090 builtin_format_patch_usage,
1091 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1092 PARSE_OPT_KEEP_DASHDASH);
1094 if (do_signoff) {
1095 const char *committer;
1096 const char *endpos;
1097 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
1098 endpos = strchr(committer, '>');
1099 if (!endpos)
1100 die("bogus committer info %s", committer);
1101 add_signoff = xmemdupz(committer, endpos - committer + 1);
1104 for (i = 0; i < extra_hdr.nr; i++) {
1105 strbuf_addstr(&buf, extra_hdr.items[i].string);
1106 strbuf_addch(&buf, '\n');
1109 if (extra_to.nr)
1110 strbuf_addstr(&buf, "To: ");
1111 for (i = 0; i < extra_to.nr; i++) {
1112 if (i)
1113 strbuf_addstr(&buf, " ");
1114 strbuf_addstr(&buf, extra_to.items[i].string);
1115 if (i + 1 < extra_to.nr)
1116 strbuf_addch(&buf, ',');
1117 strbuf_addch(&buf, '\n');
1120 if (extra_cc.nr)
1121 strbuf_addstr(&buf, "Cc: ");
1122 for (i = 0; i < extra_cc.nr; i++) {
1123 if (i)
1124 strbuf_addstr(&buf, " ");
1125 strbuf_addstr(&buf, extra_cc.items[i].string);
1126 if (i + 1 < extra_cc.nr)
1127 strbuf_addch(&buf, ',');
1128 strbuf_addch(&buf, '\n');
1131 rev.extra_headers = strbuf_detach(&buf, NULL);
1133 if (start_number < 0)
1134 start_number = 1;
1137 * If numbered is set solely due to format.numbered in config,
1138 * and it would conflict with --keep-subject (-k) from the
1139 * command line, reset "numbered".
1141 if (numbered && keep_subject && !numbered_cmdline_opt)
1142 numbered = 0;
1144 if (numbered && keep_subject)
1145 die ("-n and -k are mutually exclusive.");
1146 if (keep_subject && subject_prefix)
1147 die ("--subject-prefix and -k are mutually exclusive.");
1149 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1150 if (argc > 1)
1151 die ("unrecognized argument: %s", argv[1]);
1153 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1154 die("--name-only does not make sense");
1155 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1156 die("--name-status does not make sense");
1157 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1158 die("--check does not make sense");
1160 if (!use_patch_format &&
1161 (!rev.diffopt.output_format ||
1162 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1163 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1165 /* Always generate a patch */
1166 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1168 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1169 DIFF_OPT_SET(&rev.diffopt, BINARY);
1171 if (rev.show_notes)
1172 init_display_notes(&rev.notes_opt);
1174 if (!use_stdout)
1175 output_directory = set_outdir(prefix, output_directory);
1176 else
1177 setup_pager();
1179 if (output_directory) {
1180 if (use_stdout)
1181 die("standard output, or directory, which one?");
1182 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1183 die_errno("Could not create directory '%s'",
1184 output_directory);
1187 if (rev.pending.nr == 1) {
1188 if (rev.max_count < 0 && !rev.show_root_diff) {
1190 * This is traditional behaviour of "git format-patch
1191 * origin" that prepares what the origin side still
1192 * does not have.
1194 rev.pending.objects[0].item->flags |= UNINTERESTING;
1195 add_head_to_pending(&rev);
1198 * Otherwise, it is "format-patch -22 HEAD", and/or
1199 * "format-patch --root HEAD". The user wants
1200 * get_revision() to do the usual traversal.
1205 * We cannot move this anywhere earlier because we do want to
1206 * know if --root was given explicitly from the command line.
1208 rev.show_root_diff = 1;
1210 if (cover_letter) {
1211 /* remember the range */
1212 int i;
1213 for (i = 0; i < rev.pending.nr; i++) {
1214 struct object *o = rev.pending.objects[i].item;
1215 if (!(o->flags & UNINTERESTING))
1216 head = (struct commit *)o;
1218 /* We can't generate a cover letter without any patches */
1219 if (!head)
1220 return 0;
1223 if (ignore_if_in_upstream) {
1224 /* Don't say anything if head and upstream are the same. */
1225 if (rev.pending.nr == 2) {
1226 struct object_array_entry *o = rev.pending.objects;
1227 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1228 return 0;
1230 get_patch_ids(&rev, &ids, prefix);
1233 if (!use_stdout)
1234 realstdout = xfdopen(xdup(1), "w");
1236 if (prepare_revision_walk(&rev))
1237 die("revision walk setup failed");
1238 rev.boundary = 1;
1239 while ((commit = get_revision(&rev)) != NULL) {
1240 if (commit->object.flags & BOUNDARY) {
1241 boundary_count++;
1242 origin = (boundary_count == 1) ? commit : NULL;
1243 continue;
1246 if (ignore_if_in_upstream &&
1247 has_commit_patch_id(commit, &ids))
1248 continue;
1250 nr++;
1251 list = xrealloc(list, nr * sizeof(list[0]));
1252 list[nr - 1] = commit;
1254 total = nr;
1255 if (!keep_subject && auto_number && total > 1)
1256 numbered = 1;
1257 if (numbered)
1258 rev.total = total + start_number - 1;
1259 if (in_reply_to || thread || cover_letter)
1260 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1261 if (in_reply_to) {
1262 const char *msgid = clean_message_id(in_reply_to);
1263 string_list_append(rev.ref_message_ids, msgid);
1265 rev.numbered_files = numbered_files;
1266 rev.patch_suffix = fmt_patch_suffix;
1267 if (cover_letter) {
1268 if (thread)
1269 gen_message_id(&rev, "cover");
1270 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1271 origin, nr, list, head);
1272 total++;
1273 start_number--;
1275 rev.add_signoff = add_signoff;
1276 while (0 <= --nr) {
1277 int shown;
1278 commit = list[nr];
1279 rev.nr = total - nr + (start_number - 1);
1280 /* Make the second and subsequent mails replies to the first */
1281 if (thread) {
1282 /* Have we already had a message ID? */
1283 if (rev.message_id) {
1285 * For deep threading: make every mail
1286 * a reply to the previous one, no
1287 * matter what other options are set.
1289 * For shallow threading:
1291 * Without --cover-letter and
1292 * --in-reply-to, make every mail a
1293 * reply to the one before.
1295 * With --in-reply-to but no
1296 * --cover-letter, make every mail a
1297 * reply to the <reply-to>.
1299 * With --cover-letter, make every
1300 * mail but the cover letter a reply
1301 * to the cover letter. The cover
1302 * letter is a reply to the
1303 * --in-reply-to, if specified.
1305 if (thread == THREAD_SHALLOW
1306 && rev.ref_message_ids->nr > 0
1307 && (!cover_letter || rev.nr > 1))
1308 free(rev.message_id);
1309 else
1310 string_list_append(rev.ref_message_ids,
1311 rev.message_id);
1313 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1316 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1317 &rev))
1318 die("Failed to create output files");
1319 shown = log_tree_commit(&rev, commit);
1320 free(commit->buffer);
1321 commit->buffer = NULL;
1323 /* We put one extra blank line between formatted
1324 * patches and this flag is used by log-tree code
1325 * to see if it needs to emit a LF before showing
1326 * the log; when using one file per patch, we do
1327 * not want the extra blank line.
1329 if (!use_stdout)
1330 rev.shown_one = 0;
1331 if (shown) {
1332 if (rev.mime_boundary)
1333 printf("\n--%s%s--\n\n\n",
1334 mime_boundary_leader,
1335 rev.mime_boundary);
1336 else
1337 print_signature();
1339 if (!use_stdout)
1340 fclose(stdout);
1342 free(list);
1343 string_list_clear(&extra_to, 0);
1344 string_list_clear(&extra_cc, 0);
1345 string_list_clear(&extra_hdr, 0);
1346 if (ignore_if_in_upstream)
1347 free_patch_ids(&ids);
1348 return 0;
1351 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1353 unsigned char sha1[20];
1354 if (get_sha1(arg, sha1) == 0) {
1355 struct commit *commit = lookup_commit_reference(sha1);
1356 if (commit) {
1357 commit->object.flags |= flags;
1358 add_pending_object(revs, &commit->object, arg);
1359 return 0;
1362 return -1;
1365 static const char * const cherry_usage[] = {
1366 "git cherry [-v] [<upstream> [<head> [<limit>]]]",
1367 NULL
1370 static void print_commit(char sign, struct commit *commit, int verbose,
1371 int abbrev)
1373 if (!verbose) {
1374 printf("%c %s\n", sign,
1375 find_unique_abbrev(commit->object.sha1, abbrev));
1376 } else {
1377 struct strbuf buf = STRBUF_INIT;
1378 struct pretty_print_context ctx = {0};
1379 pretty_print_commit(CMIT_FMT_ONELINE, commit, &buf, &ctx);
1380 printf("%c %s %s\n", sign,
1381 find_unique_abbrev(commit->object.sha1, abbrev),
1382 buf.buf);
1383 strbuf_release(&buf);
1387 int cmd_cherry(int argc, const char **argv, const char *prefix)
1389 struct rev_info revs;
1390 struct patch_ids ids;
1391 struct commit *commit;
1392 struct commit_list *list = NULL;
1393 struct branch *current_branch;
1394 const char *upstream;
1395 const char *head = "HEAD";
1396 const char *limit = NULL;
1397 int verbose = 0, abbrev = 0;
1399 struct option options[] = {
1400 OPT__ABBREV(&abbrev),
1401 OPT__VERBOSE(&verbose, "be verbose"),
1402 OPT_END()
1405 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
1407 switch (argc) {
1408 case 3:
1409 limit = argv[2];
1410 /* FALLTHROUGH */
1411 case 2:
1412 head = argv[1];
1413 /* FALLTHROUGH */
1414 case 1:
1415 upstream = argv[0];
1416 break;
1417 default:
1418 current_branch = branch_get(NULL);
1419 if (!current_branch || !current_branch->merge
1420 || !current_branch->merge[0]
1421 || !current_branch->merge[0]->dst) {
1422 fprintf(stderr, "Could not find a tracked"
1423 " remote branch, please"
1424 " specify <upstream> manually.\n");
1425 usage_with_options(cherry_usage, options);
1428 upstream = current_branch->merge[0]->dst;
1431 init_revisions(&revs, prefix);
1432 revs.diff = 1;
1433 revs.combine_merges = 0;
1434 revs.ignore_merges = 1;
1435 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1437 if (add_pending_commit(head, &revs, 0))
1438 die("Unknown commit %s", head);
1439 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1440 die("Unknown commit %s", upstream);
1442 /* Don't say anything if head and upstream are the same. */
1443 if (revs.pending.nr == 2) {
1444 struct object_array_entry *o = revs.pending.objects;
1445 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1446 return 0;
1449 get_patch_ids(&revs, &ids, prefix);
1451 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1452 die("Unknown commit %s", limit);
1454 /* reverse the list of commits */
1455 if (prepare_revision_walk(&revs))
1456 die("revision walk setup failed");
1457 while ((commit = get_revision(&revs)) != NULL) {
1458 /* ignore merges */
1459 if (commit->parents && commit->parents->next)
1460 continue;
1462 commit_list_insert(commit, &list);
1465 while (list) {
1466 char sign = '+';
1468 commit = list->item;
1469 if (has_commit_patch_id(commit, &ids))
1470 sign = '-';
1471 print_commit(sign, commit, verbose, abbrev);
1472 list = list->next;
1475 free_patch_ids(&ids);
1476 return 0;