Documentation/notes: document format of notes trees
[git/gitweb.git] / builtin / log.c
blob6208703c061abb868201073795cf516bf81b2602
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 const char *fmt_patch_subject_prefix = "PATCH";
28 static const char *fmt_pretty;
30 static const char * const builtin_log_usage =
31 "git log [<options>] [<since>..<until>] [[--] <path>...]\n"
32 " or: git show [options] <object>...";
34 static void cmd_log_init(int argc, const char **argv, const char *prefix,
35 struct rev_info *rev, struct setup_revision_opt *opt)
37 int i;
38 int decoration_style = 0;
39 struct userformat_want w;
41 rev->abbrev = DEFAULT_ABBREV;
42 rev->commit_format = CMIT_FMT_DEFAULT;
43 if (fmt_pretty)
44 get_commit_format(fmt_pretty, rev);
45 rev->verbose_header = 1;
46 DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
47 rev->show_root_diff = default_show_root;
48 rev->subject_prefix = fmt_patch_subject_prefix;
49 DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
51 if (default_date_mode)
52 rev->date_mode = parse_date_format(default_date_mode);
55 * Check for -h before setup_revisions(), or "git log -h" will
56 * fail when run without a git directory.
58 if (argc == 2 && !strcmp(argv[1], "-h"))
59 usage(builtin_log_usage);
60 argc = setup_revisions(argc, argv, rev, opt);
62 memset(&w, 0, sizeof(w));
63 userformat_find_requirements(NULL, &w);
65 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
66 rev->show_notes = 1;
67 if (rev->show_notes)
68 init_display_notes(&rev->notes_opt);
70 if (rev->diffopt.pickaxe || rev->diffopt.filter)
71 rev->always_show_header = 0;
72 if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
73 rev->always_show_header = 0;
74 if (rev->diffopt.nr_paths != 1)
75 usage("git logs can only follow renames on one pathname at a time");
77 for (i = 1; i < argc; i++) {
78 const char *arg = argv[i];
79 if (!strcmp(arg, "--decorate")) {
80 decoration_style = DECORATE_SHORT_REFS;
81 } else if (!prefixcmp(arg, "--decorate=")) {
82 const char *v = skip_prefix(arg, "--decorate=");
83 if (!strcmp(v, "full"))
84 decoration_style = DECORATE_FULL_REFS;
85 else if (!strcmp(v, "short"))
86 decoration_style = DECORATE_SHORT_REFS;
87 else
88 die("invalid --decorate option: %s", arg);
89 } else if (!strcmp(arg, "--source")) {
90 rev->show_source = 1;
91 } else if (!strcmp(arg, "-h")) {
92 usage(builtin_log_usage);
93 } else
94 die("unrecognized argument: %s", arg);
96 if (decoration_style) {
97 rev->show_decorations = 1;
98 load_ref_decorations(decoration_style);
103 * This gives a rough estimate for how many commits we
104 * will print out in the list.
106 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
108 int n = 0;
110 while (list) {
111 struct commit *commit = list->item;
112 unsigned int flags = commit->object.flags;
113 list = list->next;
114 if (!(flags & (TREESAME | UNINTERESTING)))
115 n++;
117 return n;
120 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
122 if (rev->shown_one) {
123 rev->shown_one = 0;
124 if (rev->commit_format != CMIT_FMT_ONELINE)
125 putchar(rev->diffopt.line_termination);
127 printf("Final output: %d %s\n", nr, stage);
130 static struct itimerval early_output_timer;
132 static void log_show_early(struct rev_info *revs, struct commit_list *list)
134 int i = revs->early_output;
135 int show_header = 1;
137 sort_in_topological_order(&list, revs->lifo);
138 while (list && i) {
139 struct commit *commit = list->item;
140 switch (simplify_commit(revs, commit)) {
141 case commit_show:
142 if (show_header) {
143 int n = estimate_commit_count(revs, list);
144 show_early_header(revs, "incomplete", n);
145 show_header = 0;
147 log_tree_commit(revs, commit);
148 i--;
149 break;
150 case commit_ignore:
151 break;
152 case commit_error:
153 return;
155 list = list->next;
158 /* Did we already get enough commits for the early output? */
159 if (!i)
160 return;
163 * ..if no, then repeat it twice a second until we
164 * do.
166 * NOTE! We don't use "it_interval", because if the
167 * reader isn't listening, we want our output to be
168 * throttled by the writing, and not have the timer
169 * trigger every second even if we're blocked on a
170 * reader!
172 early_output_timer.it_value.tv_sec = 0;
173 early_output_timer.it_value.tv_usec = 500000;
174 setitimer(ITIMER_REAL, &early_output_timer, NULL);
177 static void early_output(int signal)
179 show_early_output = log_show_early;
182 static void setup_early_output(struct rev_info *rev)
184 struct sigaction sa;
187 * Set up the signal handler, minimally intrusively:
188 * we only set a single volatile integer word (not
189 * using sigatomic_t - trying to avoid unnecessary
190 * system dependencies and headers), and using
191 * SA_RESTART.
193 memset(&sa, 0, sizeof(sa));
194 sa.sa_handler = early_output;
195 sigemptyset(&sa.sa_mask);
196 sa.sa_flags = SA_RESTART;
197 sigaction(SIGALRM, &sa, NULL);
200 * If we can get the whole output in less than a
201 * tenth of a second, don't even bother doing the
202 * early-output thing..
204 * This is a one-time-only trigger.
206 early_output_timer.it_value.tv_sec = 0;
207 early_output_timer.it_value.tv_usec = 100000;
208 setitimer(ITIMER_REAL, &early_output_timer, NULL);
211 static void finish_early_output(struct rev_info *rev)
213 int n = estimate_commit_count(rev, rev->commits);
214 signal(SIGALRM, SIG_IGN);
215 show_early_header(rev, "done", n);
218 static int cmd_log_walk(struct rev_info *rev)
220 struct commit *commit;
222 if (rev->early_output)
223 setup_early_output(rev);
225 if (prepare_revision_walk(rev))
226 die("revision walk setup failed");
228 if (rev->early_output)
229 finish_early_output(rev);
232 * For --check and --exit-code, the exit code is based on CHECK_FAILED
233 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
234 * retain that state information if replacing rev->diffopt in this loop
236 while ((commit = get_revision(rev)) != NULL) {
237 log_tree_commit(rev, commit);
238 if (!rev->reflog_info) {
239 /* we allow cycles in reflog ancestry */
240 free(commit->buffer);
241 commit->buffer = NULL;
243 free_commit_list(commit->parents);
244 commit->parents = NULL;
246 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
247 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
248 return 02;
250 return diff_result_code(&rev->diffopt, 0);
253 static int git_log_config(const char *var, const char *value, void *cb)
255 if (!strcmp(var, "format.pretty"))
256 return git_config_string(&fmt_pretty, var, value);
257 if (!strcmp(var, "format.subjectprefix"))
258 return git_config_string(&fmt_patch_subject_prefix, var, value);
259 if (!strcmp(var, "log.date"))
260 return git_config_string(&default_date_mode, var, value);
261 if (!strcmp(var, "log.showroot")) {
262 default_show_root = git_config_bool(var, value);
263 return 0;
265 return git_diff_ui_config(var, value, cb);
268 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
270 struct rev_info rev;
271 struct setup_revision_opt opt;
273 git_config(git_log_config, NULL);
275 if (diff_use_color_default == -1)
276 diff_use_color_default = git_use_color_default;
278 init_revisions(&rev, prefix);
279 rev.diff = 1;
280 rev.simplify_history = 0;
281 memset(&opt, 0, sizeof(opt));
282 opt.def = "HEAD";
283 cmd_log_init(argc, argv, prefix, &rev, &opt);
284 if (!rev.diffopt.output_format)
285 rev.diffopt.output_format = DIFF_FORMAT_RAW;
286 return cmd_log_walk(&rev);
289 static void show_tagger(char *buf, int len, struct rev_info *rev)
291 struct strbuf out = STRBUF_INIT;
293 pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
294 git_log_output_encoding ?
295 git_log_output_encoding: git_commit_encoding);
296 printf("%s", out.buf);
297 strbuf_release(&out);
300 static int show_object(const unsigned char *sha1, int show_tag_object,
301 struct rev_info *rev)
303 unsigned long size;
304 enum object_type type;
305 char *buf = read_sha1_file(sha1, &type, &size);
306 int offset = 0;
308 if (!buf)
309 return error("Could not read object %s", sha1_to_hex(sha1));
311 if (show_tag_object)
312 while (offset < size && buf[offset] != '\n') {
313 int new_offset = offset + 1;
314 while (new_offset < size && buf[new_offset++] != '\n')
315 ; /* do nothing */
316 if (!prefixcmp(buf + offset, "tagger "))
317 show_tagger(buf + offset + 7,
318 new_offset - offset - 7, rev);
319 offset = new_offset;
322 if (offset < size)
323 fwrite(buf + offset, size - offset, 1, stdout);
324 free(buf);
325 return 0;
328 static int show_tree_object(const unsigned char *sha1,
329 const char *base, int baselen,
330 const char *pathname, unsigned mode, int stage, void *context)
332 printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
333 return 0;
336 static void show_rev_tweak_rev(struct rev_info *rev, struct setup_revision_opt *opt)
338 if (rev->ignore_merges) {
339 /* There was no "-m" on the command line */
340 rev->ignore_merges = 0;
341 if (!rev->first_parent_only && !rev->combine_merges) {
342 /* No "--first-parent", "-c", nor "--cc" */
343 rev->combine_merges = 1;
344 rev->dense_combined_merges = 1;
347 if (!rev->diffopt.output_format)
348 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
351 int cmd_show(int argc, const char **argv, const char *prefix)
353 struct rev_info rev;
354 struct object_array_entry *objects;
355 struct setup_revision_opt opt;
356 int i, count, ret = 0;
358 git_config(git_log_config, NULL);
360 if (diff_use_color_default == -1)
361 diff_use_color_default = git_use_color_default;
363 init_revisions(&rev, prefix);
364 rev.diff = 1;
365 rev.always_show_header = 1;
366 rev.no_walk = 1;
367 memset(&opt, 0, sizeof(opt));
368 opt.def = "HEAD";
369 opt.tweak = show_rev_tweak_rev;
370 cmd_log_init(argc, argv, prefix, &rev, &opt);
372 count = rev.pending.nr;
373 objects = rev.pending.objects;
374 for (i = 0; i < count && !ret; i++) {
375 struct object *o = objects[i].item;
376 const char *name = objects[i].name;
377 switch (o->type) {
378 case OBJ_BLOB:
379 ret = show_object(o->sha1, 0, NULL);
380 break;
381 case OBJ_TAG: {
382 struct tag *t = (struct tag *)o;
384 if (rev.shown_one)
385 putchar('\n');
386 printf("%stag %s%s\n",
387 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
388 t->tag,
389 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
390 ret = show_object(o->sha1, 1, &rev);
391 rev.shown_one = 1;
392 if (ret)
393 break;
394 o = parse_object(t->tagged->sha1);
395 if (!o)
396 ret = error("Could not read object %s",
397 sha1_to_hex(t->tagged->sha1));
398 objects[i].item = o;
399 i--;
400 break;
402 case OBJ_TREE:
403 if (rev.shown_one)
404 putchar('\n');
405 printf("%stree %s%s\n\n",
406 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
407 name,
408 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
409 read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
410 show_tree_object, NULL);
411 rev.shown_one = 1;
412 break;
413 case OBJ_COMMIT:
414 rev.pending.nr = rev.pending.alloc = 0;
415 rev.pending.objects = NULL;
416 add_object_array(o, name, &rev.pending);
417 ret = cmd_log_walk(&rev);
418 break;
419 default:
420 ret = error("Unknown type: %d", o->type);
423 free(objects);
424 return ret;
428 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
430 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
432 struct rev_info rev;
433 struct setup_revision_opt opt;
435 git_config(git_log_config, NULL);
437 if (diff_use_color_default == -1)
438 diff_use_color_default = git_use_color_default;
440 init_revisions(&rev, prefix);
441 init_reflog_walk(&rev.reflog_info);
442 rev.abbrev_commit = 1;
443 rev.verbose_header = 1;
444 memset(&opt, 0, sizeof(opt));
445 opt.def = "HEAD";
446 cmd_log_init(argc, argv, prefix, &rev, &opt);
449 * This means that we override whatever commit format the user gave
450 * on the cmd line. Sad, but cmd_log_init() currently doesn't
451 * allow us to set a different default.
453 rev.commit_format = CMIT_FMT_ONELINE;
454 rev.use_terminator = 1;
455 rev.always_show_header = 1;
458 * We get called through "git reflog", so unlike the other log
459 * routines, we need to set up our pager manually..
461 setup_pager();
463 return cmd_log_walk(&rev);
466 int cmd_log(int argc, const char **argv, const char *prefix)
468 struct rev_info rev;
469 struct setup_revision_opt opt;
471 git_config(git_log_config, NULL);
473 if (diff_use_color_default == -1)
474 diff_use_color_default = git_use_color_default;
476 init_revisions(&rev, prefix);
477 rev.always_show_header = 1;
478 memset(&opt, 0, sizeof(opt));
479 opt.def = "HEAD";
480 cmd_log_init(argc, argv, prefix, &rev, &opt);
481 return cmd_log_walk(&rev);
484 /* format-patch */
486 static const char *fmt_patch_suffix = ".patch";
487 static int numbered = 0;
488 static int auto_number = 1;
490 static char *default_attach = NULL;
492 static struct string_list extra_hdr;
493 static struct string_list extra_to;
494 static struct string_list extra_cc;
496 static void add_header(const char *value)
498 struct string_list_item *item;
499 int len = strlen(value);
500 while (len && value[len - 1] == '\n')
501 len--;
503 if (!strncasecmp(value, "to: ", 4)) {
504 item = string_list_append(value + 4, &extra_to);
505 len -= 4;
506 } else if (!strncasecmp(value, "cc: ", 4)) {
507 item = string_list_append(value + 4, &extra_cc);
508 len -= 4;
509 } else {
510 item = string_list_append(value, &extra_hdr);
513 item->string[len] = '\0';
516 #define THREAD_SHALLOW 1
517 #define THREAD_DEEP 2
518 static int thread = 0;
519 static int do_signoff = 0;
521 static int git_format_config(const char *var, const char *value, void *cb)
523 if (!strcmp(var, "format.headers")) {
524 if (!value)
525 die("format.headers without value");
526 add_header(value);
527 return 0;
529 if (!strcmp(var, "format.suffix"))
530 return git_config_string(&fmt_patch_suffix, var, value);
531 if (!strcmp(var, "format.to")) {
532 if (!value)
533 return config_error_nonbool(var);
534 string_list_append(value, &extra_to);
535 return 0;
537 if (!strcmp(var, "format.cc")) {
538 if (!value)
539 return config_error_nonbool(var);
540 string_list_append(value, &extra_cc);
541 return 0;
543 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
544 return 0;
546 if (!strcmp(var, "format.numbered")) {
547 if (value && !strcasecmp(value, "auto")) {
548 auto_number = 1;
549 return 0;
551 numbered = git_config_bool(var, value);
552 auto_number = auto_number && numbered;
553 return 0;
555 if (!strcmp(var, "format.attach")) {
556 if (value && *value)
557 default_attach = xstrdup(value);
558 else
559 default_attach = xstrdup(git_version_string);
560 return 0;
562 if (!strcmp(var, "format.thread")) {
563 if (value && !strcasecmp(value, "deep")) {
564 thread = THREAD_DEEP;
565 return 0;
567 if (value && !strcasecmp(value, "shallow")) {
568 thread = THREAD_SHALLOW;
569 return 0;
571 thread = git_config_bool(var, value) && THREAD_SHALLOW;
572 return 0;
574 if (!strcmp(var, "format.signoff")) {
575 do_signoff = git_config_bool(var, value);
576 return 0;
579 return git_log_config(var, value, cb);
582 static FILE *realstdout = NULL;
583 static const char *output_directory = NULL;
584 static int outdir_offset;
586 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
588 struct strbuf filename = STRBUF_INIT;
589 int suffix_len = strlen(fmt_patch_suffix) + 1;
591 if (output_directory) {
592 strbuf_addstr(&filename, output_directory);
593 if (filename.len >=
594 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
595 return error("name of output directory is too long");
596 if (filename.buf[filename.len - 1] != '/')
597 strbuf_addch(&filename, '/');
600 get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
602 if (!DIFF_OPT_TST(&rev->diffopt, QUICK))
603 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
605 if (freopen(filename.buf, "w", stdout) == NULL)
606 return error("Cannot open patch file %s", filename.buf);
608 strbuf_release(&filename);
609 return 0;
612 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
614 struct rev_info check_rev;
615 struct commit *commit;
616 struct object *o1, *o2;
617 unsigned flags1, flags2;
619 if (rev->pending.nr != 2)
620 die("Need exactly one range.");
622 o1 = rev->pending.objects[0].item;
623 flags1 = o1->flags;
624 o2 = rev->pending.objects[1].item;
625 flags2 = o2->flags;
627 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
628 die("Not a range.");
630 init_patch_ids(ids);
632 /* given a range a..b get all patch ids for b..a */
633 init_revisions(&check_rev, prefix);
634 o1->flags ^= UNINTERESTING;
635 o2->flags ^= UNINTERESTING;
636 add_pending_object(&check_rev, o1, "o1");
637 add_pending_object(&check_rev, o2, "o2");
638 if (prepare_revision_walk(&check_rev))
639 die("revision walk setup failed");
641 while ((commit = get_revision(&check_rev)) != NULL) {
642 /* ignore merges */
643 if (commit->parents && commit->parents->next)
644 continue;
646 add_commit_patch_id(commit, ids);
649 /* reset for next revision walk */
650 clear_commit_marks((struct commit *)o1,
651 SEEN | UNINTERESTING | SHOWN | ADDED);
652 clear_commit_marks((struct commit *)o2,
653 SEEN | UNINTERESTING | SHOWN | ADDED);
654 o1->flags = flags1;
655 o2->flags = flags2;
658 static void gen_message_id(struct rev_info *info, char *base)
660 const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
661 const char *email_start = strrchr(committer, '<');
662 const char *email_end = strrchr(committer, '>');
663 struct strbuf buf = STRBUF_INIT;
664 if (!email_start || !email_end || email_start > email_end - 1)
665 die("Could not extract email from committer identity.");
666 strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
667 (unsigned long) time(NULL),
668 (int)(email_end - email_start - 1), email_start + 1);
669 info->message_id = strbuf_detach(&buf, NULL);
672 static void make_cover_letter(struct rev_info *rev, int use_stdout,
673 int numbered, int numbered_files,
674 struct commit *origin,
675 int nr, struct commit **list, struct commit *head)
677 const char *committer;
678 const char *subject_start = NULL;
679 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
680 const char *msg;
681 const char *extra_headers = rev->extra_headers;
682 struct shortlog log;
683 struct strbuf sb = STRBUF_INIT;
684 int i;
685 const char *encoding = "UTF-8";
686 struct diff_options opts;
687 int need_8bit_cte = 0;
688 struct commit *commit = NULL;
690 if (rev->commit_format != CMIT_FMT_EMAIL)
691 die("Cover letter needs email format");
693 committer = git_committer_info(0);
695 if (!numbered_files) {
697 * We fake a commit for the cover letter so we get the filename
698 * desired.
700 commit = xcalloc(1, sizeof(*commit));
701 commit->buffer = xmalloc(400);
702 snprintf(commit->buffer, 400,
703 "tree 0000000000000000000000000000000000000000\n"
704 "parent %s\n"
705 "author %s\n"
706 "committer %s\n\n"
707 "cover letter\n",
708 sha1_to_hex(head->object.sha1), committer, committer);
711 if (!use_stdout && reopen_stdout(commit, rev))
712 return;
714 if (commit) {
716 free(commit->buffer);
717 free(commit);
720 log_write_email_headers(rev, head, &subject_start, &extra_headers,
721 &need_8bit_cte);
723 for (i = 0; !need_8bit_cte && i < nr; i++)
724 if (has_non_ascii(list[i]->buffer))
725 need_8bit_cte = 1;
727 msg = body;
728 pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
729 encoding);
730 pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
731 encoding, need_8bit_cte);
732 pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
733 printf("%s\n", sb.buf);
735 strbuf_release(&sb);
737 shortlog_init(&log);
738 log.wrap_lines = 1;
739 log.wrap = 72;
740 log.in1 = 2;
741 log.in2 = 4;
742 for (i = 0; i < nr; i++)
743 shortlog_add_commit(&log, list[i]);
745 shortlog_output(&log);
748 * We can only do diffstat with a unique reference point
750 if (!origin)
751 return;
753 memcpy(&opts, &rev->diffopt, sizeof(opts));
754 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
756 diff_setup_done(&opts);
758 diff_tree_sha1(origin->tree->object.sha1,
759 head->tree->object.sha1,
760 "", &opts);
761 diffcore_std(&opts);
762 diff_flush(&opts);
764 printf("\n");
767 static const char *clean_message_id(const char *msg_id)
769 char ch;
770 const char *a, *z, *m;
772 m = msg_id;
773 while ((ch = *m) && (isspace(ch) || (ch == '<')))
774 m++;
775 a = m;
776 z = NULL;
777 while ((ch = *m)) {
778 if (!isspace(ch) && (ch != '>'))
779 z = m;
780 m++;
782 if (!z)
783 die("insane in-reply-to: %s", msg_id);
784 if (++z == m)
785 return a;
786 return xmemdupz(a, z - a);
789 static const char *set_outdir(const char *prefix, const char *output_directory)
791 if (output_directory && is_absolute_path(output_directory))
792 return output_directory;
794 if (!prefix || !*prefix) {
795 if (output_directory)
796 return output_directory;
797 /* The user did not explicitly ask for "./" */
798 outdir_offset = 2;
799 return "./";
802 outdir_offset = strlen(prefix);
803 if (!output_directory)
804 return prefix;
806 return xstrdup(prefix_filename(prefix, outdir_offset,
807 output_directory));
810 static const char * const builtin_format_patch_usage[] = {
811 "git format-patch [options] [<since> | <revision range>]",
812 NULL
815 static int keep_subject = 0;
817 static int keep_callback(const struct option *opt, const char *arg, int unset)
819 ((struct rev_info *)opt->value)->total = -1;
820 keep_subject = 1;
821 return 0;
824 static int subject_prefix = 0;
826 static int subject_prefix_callback(const struct option *opt, const char *arg,
827 int unset)
829 subject_prefix = 1;
830 ((struct rev_info *)opt->value)->subject_prefix = arg;
831 return 0;
834 static int numbered_cmdline_opt = 0;
836 static int numbered_callback(const struct option *opt, const char *arg,
837 int unset)
839 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
840 if (unset)
841 auto_number = 0;
842 return 0;
845 static int no_numbered_callback(const struct option *opt, const char *arg,
846 int unset)
848 return numbered_callback(opt, arg, 1);
851 static int output_directory_callback(const struct option *opt, const char *arg,
852 int unset)
854 const char **dir = (const char **)opt->value;
855 if (*dir)
856 die("Two output directories?");
857 *dir = arg;
858 return 0;
861 static int thread_callback(const struct option *opt, const char *arg, int unset)
863 int *thread = (int *)opt->value;
864 if (unset)
865 *thread = 0;
866 else if (!arg || !strcmp(arg, "shallow"))
867 *thread = THREAD_SHALLOW;
868 else if (!strcmp(arg, "deep"))
869 *thread = THREAD_DEEP;
870 else
871 return 1;
872 return 0;
875 static int attach_callback(const struct option *opt, const char *arg, int unset)
877 struct rev_info *rev = (struct rev_info *)opt->value;
878 if (unset)
879 rev->mime_boundary = NULL;
880 else if (arg)
881 rev->mime_boundary = arg;
882 else
883 rev->mime_boundary = git_version_string;
884 rev->no_inline = unset ? 0 : 1;
885 return 0;
888 static int inline_callback(const struct option *opt, const char *arg, int unset)
890 struct rev_info *rev = (struct rev_info *)opt->value;
891 if (unset)
892 rev->mime_boundary = NULL;
893 else if (arg)
894 rev->mime_boundary = arg;
895 else
896 rev->mime_boundary = git_version_string;
897 rev->no_inline = 0;
898 return 0;
901 static int header_callback(const struct option *opt, const char *arg, int unset)
903 if (unset) {
904 string_list_clear(&extra_hdr, 0);
905 string_list_clear(&extra_to, 0);
906 string_list_clear(&extra_cc, 0);
907 } else {
908 add_header(arg);
910 return 0;
913 static int to_callback(const struct option *opt, const char *arg, int unset)
915 if (unset)
916 string_list_clear(&extra_to, 0);
917 else
918 string_list_append(arg, &extra_to);
919 return 0;
922 static int cc_callback(const struct option *opt, const char *arg, int unset)
924 if (unset)
925 string_list_clear(&extra_cc, 0);
926 else
927 string_list_append(arg, &extra_cc);
928 return 0;
931 int cmd_format_patch(int argc, const char **argv, const char *prefix)
933 struct commit *commit;
934 struct commit **list = NULL;
935 struct rev_info rev;
936 struct setup_revision_opt s_r_opt;
937 int nr = 0, total, i;
938 int use_stdout = 0;
939 int start_number = -1;
940 int numbered_files = 0; /* _just_ numbers */
941 int ignore_if_in_upstream = 0;
942 int cover_letter = 0;
943 int boundary_count = 0;
944 int no_binary_diff = 0;
945 struct commit *origin = NULL, *head = NULL;
946 const char *in_reply_to = NULL;
947 struct patch_ids ids;
948 char *add_signoff = NULL;
949 struct strbuf buf = STRBUF_INIT;
950 int use_patch_format = 0;
951 const struct option builtin_format_patch_options[] = {
952 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
953 "use [PATCH n/m] even with a single patch",
954 PARSE_OPT_NOARG, numbered_callback },
955 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
956 "use [PATCH] even with multiple patches",
957 PARSE_OPT_NOARG, no_numbered_callback },
958 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
959 OPT_BOOLEAN(0, "stdout", &use_stdout,
960 "print patches to standard out"),
961 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
962 "generate a cover letter"),
963 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
964 "use simple number sequence for output file names"),
965 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
966 "use <sfx> instead of '.patch'"),
967 OPT_INTEGER(0, "start-number", &start_number,
968 "start numbering patches at <n> instead of 1"),
969 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
970 "Use [<prefix>] instead of [PATCH]",
971 PARSE_OPT_NONEG, subject_prefix_callback },
972 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
973 "dir", "store resulting files in <dir>",
974 PARSE_OPT_NONEG, output_directory_callback },
975 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
976 "don't strip/add [PATCH]",
977 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
978 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
979 "don't output binary diffs"),
980 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
981 "don't include a patch matching a commit upstream"),
982 { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
983 "show patch format instead of default (patch + stat)",
984 PARSE_OPT_NONEG | PARSE_OPT_NOARG },
985 OPT_GROUP("Messaging"),
986 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
987 "add email header", 0, header_callback },
988 { OPTION_CALLBACK, 0, "to", NULL, "email", "add To: header",
989 0, to_callback },
990 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
991 0, cc_callback },
992 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
993 "make first mail a reply to <message-id>"),
994 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
995 "attach the patch", PARSE_OPT_OPTARG,
996 attach_callback },
997 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
998 "inline the patch",
999 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1000 inline_callback },
1001 { OPTION_CALLBACK, 0, "thread", &thread, "style",
1002 "enable message threading, styles: shallow, deep",
1003 PARSE_OPT_OPTARG, thread_callback },
1004 OPT_END()
1007 extra_hdr.strdup_strings = 1;
1008 extra_to.strdup_strings = 1;
1009 extra_cc.strdup_strings = 1;
1010 git_config(git_format_config, NULL);
1011 init_revisions(&rev, prefix);
1012 rev.commit_format = CMIT_FMT_EMAIL;
1013 rev.verbose_header = 1;
1014 rev.diff = 1;
1015 rev.combine_merges = 0;
1016 rev.ignore_merges = 1;
1017 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1018 rev.subject_prefix = fmt_patch_subject_prefix;
1019 memset(&s_r_opt, 0, sizeof(s_r_opt));
1020 s_r_opt.def = "HEAD";
1022 if (default_attach) {
1023 rev.mime_boundary = default_attach;
1024 rev.no_inline = 1;
1028 * Parse the arguments before setup_revisions(), or something
1029 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1030 * possibly a valid SHA1.
1032 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1033 builtin_format_patch_usage,
1034 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1035 PARSE_OPT_KEEP_DASHDASH);
1037 if (do_signoff) {
1038 const char *committer;
1039 const char *endpos;
1040 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
1041 endpos = strchr(committer, '>');
1042 if (!endpos)
1043 die("bogus committer info %s", committer);
1044 add_signoff = xmemdupz(committer, endpos - committer + 1);
1047 for (i = 0; i < extra_hdr.nr; i++) {
1048 strbuf_addstr(&buf, extra_hdr.items[i].string);
1049 strbuf_addch(&buf, '\n');
1052 if (extra_to.nr)
1053 strbuf_addstr(&buf, "To: ");
1054 for (i = 0; i < extra_to.nr; i++) {
1055 if (i)
1056 strbuf_addstr(&buf, " ");
1057 strbuf_addstr(&buf, extra_to.items[i].string);
1058 if (i + 1 < extra_to.nr)
1059 strbuf_addch(&buf, ',');
1060 strbuf_addch(&buf, '\n');
1063 if (extra_cc.nr)
1064 strbuf_addstr(&buf, "Cc: ");
1065 for (i = 0; i < extra_cc.nr; i++) {
1066 if (i)
1067 strbuf_addstr(&buf, " ");
1068 strbuf_addstr(&buf, extra_cc.items[i].string);
1069 if (i + 1 < extra_cc.nr)
1070 strbuf_addch(&buf, ',');
1071 strbuf_addch(&buf, '\n');
1074 rev.extra_headers = strbuf_detach(&buf, NULL);
1076 if (start_number < 0)
1077 start_number = 1;
1080 * If numbered is set solely due to format.numbered in config,
1081 * and it would conflict with --keep-subject (-k) from the
1082 * command line, reset "numbered".
1084 if (numbered && keep_subject && !numbered_cmdline_opt)
1085 numbered = 0;
1087 if (numbered && keep_subject)
1088 die ("-n and -k are mutually exclusive.");
1089 if (keep_subject && subject_prefix)
1090 die ("--subject-prefix and -k are mutually exclusive.");
1092 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1093 if (argc > 1)
1094 die ("unrecognized argument: %s", argv[1]);
1096 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1097 die("--name-only does not make sense");
1098 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1099 die("--name-status does not make sense");
1100 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1101 die("--check does not make sense");
1103 if (!use_patch_format &&
1104 (!rev.diffopt.output_format ||
1105 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1106 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1108 /* Always generate a patch */
1109 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1111 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1112 DIFF_OPT_SET(&rev.diffopt, BINARY);
1114 if (rev.show_notes)
1115 init_display_notes(&rev.notes_opt);
1117 if (!use_stdout)
1118 output_directory = set_outdir(prefix, output_directory);
1120 if (output_directory) {
1121 if (use_stdout)
1122 die("standard output, or directory, which one?");
1123 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1124 die_errno("Could not create directory '%s'",
1125 output_directory);
1128 if (rev.pending.nr == 1) {
1129 if (rev.max_count < 0 && !rev.show_root_diff) {
1131 * This is traditional behaviour of "git format-patch
1132 * origin" that prepares what the origin side still
1133 * does not have.
1135 rev.pending.objects[0].item->flags |= UNINTERESTING;
1136 add_head_to_pending(&rev);
1139 * Otherwise, it is "format-patch -22 HEAD", and/or
1140 * "format-patch --root HEAD". The user wants
1141 * get_revision() to do the usual traversal.
1146 * We cannot move this anywhere earlier because we do want to
1147 * know if --root was given explicitly from the command line.
1149 rev.show_root_diff = 1;
1151 if (cover_letter) {
1152 /* remember the range */
1153 int i;
1154 for (i = 0; i < rev.pending.nr; i++) {
1155 struct object *o = rev.pending.objects[i].item;
1156 if (!(o->flags & UNINTERESTING))
1157 head = (struct commit *)o;
1159 /* We can't generate a cover letter without any patches */
1160 if (!head)
1161 return 0;
1164 if (ignore_if_in_upstream) {
1165 /* Don't say anything if head and upstream are the same. */
1166 if (rev.pending.nr == 2) {
1167 struct object_array_entry *o = rev.pending.objects;
1168 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1169 return 0;
1171 get_patch_ids(&rev, &ids, prefix);
1174 if (!use_stdout)
1175 realstdout = xfdopen(xdup(1), "w");
1177 if (prepare_revision_walk(&rev))
1178 die("revision walk setup failed");
1179 rev.boundary = 1;
1180 while ((commit = get_revision(&rev)) != NULL) {
1181 if (commit->object.flags & BOUNDARY) {
1182 boundary_count++;
1183 origin = (boundary_count == 1) ? commit : NULL;
1184 continue;
1187 /* ignore merges */
1188 if (commit->parents && commit->parents->next)
1189 continue;
1191 if (ignore_if_in_upstream &&
1192 has_commit_patch_id(commit, &ids))
1193 continue;
1195 nr++;
1196 list = xrealloc(list, nr * sizeof(list[0]));
1197 list[nr - 1] = commit;
1199 total = nr;
1200 if (!keep_subject && auto_number && total > 1)
1201 numbered = 1;
1202 if (numbered)
1203 rev.total = total + start_number - 1;
1204 if (in_reply_to || thread || cover_letter)
1205 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1206 if (in_reply_to) {
1207 const char *msgid = clean_message_id(in_reply_to);
1208 string_list_append(msgid, rev.ref_message_ids);
1210 rev.numbered_files = numbered_files;
1211 rev.patch_suffix = fmt_patch_suffix;
1212 if (cover_letter) {
1213 if (thread)
1214 gen_message_id(&rev, "cover");
1215 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1216 origin, nr, list, head);
1217 total++;
1218 start_number--;
1220 rev.add_signoff = add_signoff;
1221 while (0 <= --nr) {
1222 int shown;
1223 commit = list[nr];
1224 rev.nr = total - nr + (start_number - 1);
1225 /* Make the second and subsequent mails replies to the first */
1226 if (thread) {
1227 /* Have we already had a message ID? */
1228 if (rev.message_id) {
1230 * For deep threading: make every mail
1231 * a reply to the previous one, no
1232 * matter what other options are set.
1234 * For shallow threading:
1236 * Without --cover-letter and
1237 * --in-reply-to, make every mail a
1238 * reply to the one before.
1240 * With --in-reply-to but no
1241 * --cover-letter, make every mail a
1242 * reply to the <reply-to>.
1244 * With --cover-letter, make every
1245 * mail but the cover letter a reply
1246 * to the cover letter. The cover
1247 * letter is a reply to the
1248 * --in-reply-to, if specified.
1250 if (thread == THREAD_SHALLOW
1251 && rev.ref_message_ids->nr > 0
1252 && (!cover_letter || rev.nr > 1))
1253 free(rev.message_id);
1254 else
1255 string_list_append(rev.message_id,
1256 rev.ref_message_ids);
1258 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1261 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1262 &rev))
1263 die("Failed to create output files");
1264 shown = log_tree_commit(&rev, commit);
1265 free(commit->buffer);
1266 commit->buffer = NULL;
1268 /* We put one extra blank line between formatted
1269 * patches and this flag is used by log-tree code
1270 * to see if it needs to emit a LF before showing
1271 * the log; when using one file per patch, we do
1272 * not want the extra blank line.
1274 if (!use_stdout)
1275 rev.shown_one = 0;
1276 if (shown) {
1277 if (rev.mime_boundary)
1278 printf("\n--%s%s--\n\n\n",
1279 mime_boundary_leader,
1280 rev.mime_boundary);
1281 else
1282 printf("-- \n%s\n\n", git_version_string);
1284 if (!use_stdout)
1285 fclose(stdout);
1287 free(list);
1288 string_list_clear(&extra_to, 0);
1289 string_list_clear(&extra_cc, 0);
1290 string_list_clear(&extra_hdr, 0);
1291 if (ignore_if_in_upstream)
1292 free_patch_ids(&ids);
1293 return 0;
1296 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1298 unsigned char sha1[20];
1299 if (get_sha1(arg, sha1) == 0) {
1300 struct commit *commit = lookup_commit_reference(sha1);
1301 if (commit) {
1302 commit->object.flags |= flags;
1303 add_pending_object(revs, &commit->object, arg);
1304 return 0;
1307 return -1;
1310 static const char * const cherry_usage[] = {
1311 "git cherry [-v] [<upstream> [<head> [<limit>]]]",
1312 NULL
1315 int cmd_cherry(int argc, const char **argv, const char *prefix)
1317 struct rev_info revs;
1318 struct patch_ids ids;
1319 struct commit *commit;
1320 struct commit_list *list = NULL;
1321 struct branch *current_branch;
1322 const char *upstream;
1323 const char *head = "HEAD";
1324 const char *limit = NULL;
1325 int verbose = 0, abbrev = 0;
1327 struct option options[] = {
1328 OPT__ABBREV(&abbrev),
1329 OPT__VERBOSE(&verbose),
1330 OPT_END()
1333 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
1335 switch (argc) {
1336 case 3:
1337 limit = argv[2];
1338 /* FALLTHROUGH */
1339 case 2:
1340 head = argv[1];
1341 /* FALLTHROUGH */
1342 case 1:
1343 upstream = argv[0];
1344 break;
1345 default:
1346 current_branch = branch_get(NULL);
1347 if (!current_branch || !current_branch->merge
1348 || !current_branch->merge[0]
1349 || !current_branch->merge[0]->dst) {
1350 fprintf(stderr, "Could not find a tracked"
1351 " remote branch, please"
1352 " specify <upstream> manually.\n");
1353 usage_with_options(cherry_usage, options);
1356 upstream = current_branch->merge[0]->dst;
1359 init_revisions(&revs, prefix);
1360 revs.diff = 1;
1361 revs.combine_merges = 0;
1362 revs.ignore_merges = 1;
1363 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1365 if (add_pending_commit(head, &revs, 0))
1366 die("Unknown commit %s", head);
1367 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1368 die("Unknown commit %s", upstream);
1370 /* Don't say anything if head and upstream are the same. */
1371 if (revs.pending.nr == 2) {
1372 struct object_array_entry *o = revs.pending.objects;
1373 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1374 return 0;
1377 get_patch_ids(&revs, &ids, prefix);
1379 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1380 die("Unknown commit %s", limit);
1382 /* reverse the list of commits */
1383 if (prepare_revision_walk(&revs))
1384 die("revision walk setup failed");
1385 while ((commit = get_revision(&revs)) != NULL) {
1386 /* ignore merges */
1387 if (commit->parents && commit->parents->next)
1388 continue;
1390 commit_list_insert(commit, &list);
1393 while (list) {
1394 char sign = '+';
1396 commit = list->item;
1397 if (has_commit_patch_id(commit, &ids))
1398 sign = '-';
1400 if (verbose) {
1401 struct strbuf buf = STRBUF_INIT;
1402 struct pretty_print_context ctx = {0};
1403 pretty_print_commit(CMIT_FMT_ONELINE, commit,
1404 &buf, &ctx);
1405 printf("%c %s %s\n", sign,
1406 find_unique_abbrev(commit->object.sha1, abbrev),
1407 buf.buf);
1408 strbuf_release(&buf);
1410 else {
1411 printf("%c %s\n", sign,
1412 find_unique_abbrev(commit->object.sha1, abbrev));
1415 list = list->next;
1418 free_patch_ids(&ids);
1419 return 0;