Merge branch 'pb/log-first-parent-p-m'
[git/mingw.git] / builtin / log.c
blobfade77200f14514950c727bae7af402d7174f11a
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;
40 rev->abbrev = DEFAULT_ABBREV;
41 rev->commit_format = CMIT_FMT_DEFAULT;
42 if (fmt_pretty)
43 get_commit_format(fmt_pretty, rev);
44 rev->verbose_header = 1;
45 DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
46 rev->show_root_diff = default_show_root;
47 rev->subject_prefix = fmt_patch_subject_prefix;
48 DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
50 if (default_date_mode)
51 rev->date_mode = parse_date_format(default_date_mode);
54 * Check for -h before setup_revisions(), or "git log -h" will
55 * fail when run without a git directory.
57 if (argc == 2 && !strcmp(argv[1], "-h"))
58 usage(builtin_log_usage);
59 argc = setup_revisions(argc, argv, rev, opt);
61 if (!rev->show_notes_given && !rev->pretty_given)
62 rev->show_notes = 1;
64 if (rev->diffopt.pickaxe || rev->diffopt.filter)
65 rev->always_show_header = 0;
66 if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
67 rev->always_show_header = 0;
68 if (rev->diffopt.nr_paths != 1)
69 usage("git logs can only follow renames on one pathname at a time");
71 for (i = 1; i < argc; i++) {
72 const char *arg = argv[i];
73 if (!strcmp(arg, "--decorate")) {
74 decoration_style = DECORATE_SHORT_REFS;
75 } else if (!prefixcmp(arg, "--decorate=")) {
76 const char *v = skip_prefix(arg, "--decorate=");
77 if (!strcmp(v, "full"))
78 decoration_style = DECORATE_FULL_REFS;
79 else if (!strcmp(v, "short"))
80 decoration_style = DECORATE_SHORT_REFS;
81 else
82 die("invalid --decorate option: %s", arg);
83 } else if (!strcmp(arg, "--source")) {
84 rev->show_source = 1;
85 } else if (!strcmp(arg, "-h")) {
86 usage(builtin_log_usage);
87 } else
88 die("unrecognized argument: %s", arg);
90 if (decoration_style) {
91 rev->show_decorations = 1;
92 load_ref_decorations(decoration_style);
97 * This gives a rough estimate for how many commits we
98 * will print out in the list.
100 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
102 int n = 0;
104 while (list) {
105 struct commit *commit = list->item;
106 unsigned int flags = commit->object.flags;
107 list = list->next;
108 if (!(flags & (TREESAME | UNINTERESTING)))
109 n++;
111 return n;
114 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
116 if (rev->shown_one) {
117 rev->shown_one = 0;
118 if (rev->commit_format != CMIT_FMT_ONELINE)
119 putchar(rev->diffopt.line_termination);
121 printf("Final output: %d %s\n", nr, stage);
124 static struct itimerval early_output_timer;
126 static void log_show_early(struct rev_info *revs, struct commit_list *list)
128 int i = revs->early_output;
129 int show_header = 1;
131 sort_in_topological_order(&list, revs->lifo);
132 while (list && i) {
133 struct commit *commit = list->item;
134 switch (simplify_commit(revs, commit)) {
135 case commit_show:
136 if (show_header) {
137 int n = estimate_commit_count(revs, list);
138 show_early_header(revs, "incomplete", n);
139 show_header = 0;
141 log_tree_commit(revs, commit);
142 i--;
143 break;
144 case commit_ignore:
145 break;
146 case commit_error:
147 return;
149 list = list->next;
152 /* Did we already get enough commits for the early output? */
153 if (!i)
154 return;
157 * ..if no, then repeat it twice a second until we
158 * do.
160 * NOTE! We don't use "it_interval", because if the
161 * reader isn't listening, we want our output to be
162 * throttled by the writing, and not have the timer
163 * trigger every second even if we're blocked on a
164 * reader!
166 early_output_timer.it_value.tv_sec = 0;
167 early_output_timer.it_value.tv_usec = 500000;
168 setitimer(ITIMER_REAL, &early_output_timer, NULL);
171 static void early_output(int signal)
173 show_early_output = log_show_early;
176 static void setup_early_output(struct rev_info *rev)
178 struct sigaction sa;
181 * Set up the signal handler, minimally intrusively:
182 * we only set a single volatile integer word (not
183 * using sigatomic_t - trying to avoid unnecessary
184 * system dependencies and headers), and using
185 * SA_RESTART.
187 memset(&sa, 0, sizeof(sa));
188 sa.sa_handler = early_output;
189 sigemptyset(&sa.sa_mask);
190 sa.sa_flags = SA_RESTART;
191 sigaction(SIGALRM, &sa, NULL);
194 * If we can get the whole output in less than a
195 * tenth of a second, don't even bother doing the
196 * early-output thing..
198 * This is a one-time-only trigger.
200 early_output_timer.it_value.tv_sec = 0;
201 early_output_timer.it_value.tv_usec = 100000;
202 setitimer(ITIMER_REAL, &early_output_timer, NULL);
205 static void finish_early_output(struct rev_info *rev)
207 int n = estimate_commit_count(rev, rev->commits);
208 signal(SIGALRM, SIG_IGN);
209 show_early_header(rev, "done", n);
212 static int cmd_log_walk(struct rev_info *rev)
214 struct commit *commit;
216 if (rev->early_output)
217 setup_early_output(rev);
219 if (prepare_revision_walk(rev))
220 die("revision walk setup failed");
222 if (rev->early_output)
223 finish_early_output(rev);
226 * For --check and --exit-code, the exit code is based on CHECK_FAILED
227 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
228 * retain that state information if replacing rev->diffopt in this loop
230 while ((commit = get_revision(rev)) != NULL) {
231 log_tree_commit(rev, commit);
232 if (!rev->reflog_info) {
233 /* we allow cycles in reflog ancestry */
234 free(commit->buffer);
235 commit->buffer = NULL;
237 free_commit_list(commit->parents);
238 commit->parents = NULL;
240 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
241 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
242 return 02;
244 return diff_result_code(&rev->diffopt, 0);
247 static int git_log_config(const char *var, const char *value, void *cb)
249 if (!strcmp(var, "format.pretty"))
250 return git_config_string(&fmt_pretty, var, value);
251 if (!strcmp(var, "format.subjectprefix"))
252 return git_config_string(&fmt_patch_subject_prefix, var, value);
253 if (!strcmp(var, "log.date"))
254 return git_config_string(&default_date_mode, var, value);
255 if (!strcmp(var, "log.showroot")) {
256 default_show_root = git_config_bool(var, value);
257 return 0;
259 return git_diff_ui_config(var, value, cb);
262 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
264 struct rev_info rev;
265 struct setup_revision_opt opt;
267 git_config(git_log_config, NULL);
269 if (diff_use_color_default == -1)
270 diff_use_color_default = git_use_color_default;
272 init_revisions(&rev, prefix);
273 rev.diff = 1;
274 rev.simplify_history = 0;
275 memset(&opt, 0, sizeof(opt));
276 opt.def = "HEAD";
277 cmd_log_init(argc, argv, prefix, &rev, &opt);
278 if (!rev.diffopt.output_format)
279 rev.diffopt.output_format = DIFF_FORMAT_RAW;
280 return cmd_log_walk(&rev);
283 static void show_tagger(char *buf, int len, struct rev_info *rev)
285 struct strbuf out = STRBUF_INIT;
287 pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
288 git_log_output_encoding ?
289 git_log_output_encoding: git_commit_encoding);
290 printf("%s", out.buf);
291 strbuf_release(&out);
294 static int show_object(const unsigned char *sha1, int show_tag_object,
295 struct rev_info *rev)
297 unsigned long size;
298 enum object_type type;
299 char *buf = read_sha1_file(sha1, &type, &size);
300 int offset = 0;
302 if (!buf)
303 return error("Could not read object %s", sha1_to_hex(sha1));
305 if (show_tag_object)
306 while (offset < size && buf[offset] != '\n') {
307 int new_offset = offset + 1;
308 while (new_offset < size && buf[new_offset++] != '\n')
309 ; /* do nothing */
310 if (!prefixcmp(buf + offset, "tagger "))
311 show_tagger(buf + offset + 7,
312 new_offset - offset - 7, rev);
313 offset = new_offset;
316 if (offset < size)
317 fwrite(buf + offset, size - offset, 1, stdout);
318 free(buf);
319 return 0;
322 static int show_tree_object(const unsigned char *sha1,
323 const char *base, int baselen,
324 const char *pathname, unsigned mode, int stage, void *context)
326 printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
327 return 0;
330 static void show_rev_tweak_rev(struct rev_info *rev, struct setup_revision_opt *opt)
332 if (rev->ignore_merges) {
333 /* There was no "-m" on the command line */
334 rev->ignore_merges = 0;
335 if (!rev->first_parent_only && !rev->combine_merges) {
336 /* No "--first-parent", "-c", nor "--cc" */
337 rev->combine_merges = 1;
338 rev->dense_combined_merges = 1;
341 if (!rev->diffopt.output_format)
342 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
345 int cmd_show(int argc, const char **argv, const char *prefix)
347 struct rev_info rev;
348 struct object_array_entry *objects;
349 struct setup_revision_opt opt;
350 int i, count, ret = 0;
352 git_config(git_log_config, NULL);
354 if (diff_use_color_default == -1)
355 diff_use_color_default = git_use_color_default;
357 init_revisions(&rev, prefix);
358 rev.diff = 1;
359 rev.always_show_header = 1;
360 rev.no_walk = 1;
361 memset(&opt, 0, sizeof(opt));
362 opt.def = "HEAD";
363 opt.tweak = show_rev_tweak_rev;
364 cmd_log_init(argc, argv, prefix, &rev, &opt);
366 count = rev.pending.nr;
367 objects = rev.pending.objects;
368 for (i = 0; i < count && !ret; i++) {
369 struct object *o = objects[i].item;
370 const char *name = objects[i].name;
371 switch (o->type) {
372 case OBJ_BLOB:
373 ret = show_object(o->sha1, 0, NULL);
374 break;
375 case OBJ_TAG: {
376 struct tag *t = (struct tag *)o;
378 if (rev.shown_one)
379 putchar('\n');
380 printf("%stag %s%s\n",
381 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
382 t->tag,
383 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
384 ret = show_object(o->sha1, 1, &rev);
385 rev.shown_one = 1;
386 if (ret)
387 break;
388 o = parse_object(t->tagged->sha1);
389 if (!o)
390 ret = error("Could not read object %s",
391 sha1_to_hex(t->tagged->sha1));
392 objects[i].item = o;
393 i--;
394 break;
396 case OBJ_TREE:
397 if (rev.shown_one)
398 putchar('\n');
399 printf("%stree %s%s\n\n",
400 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
401 name,
402 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
403 read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
404 show_tree_object, NULL);
405 rev.shown_one = 1;
406 break;
407 case OBJ_COMMIT:
408 rev.pending.nr = rev.pending.alloc = 0;
409 rev.pending.objects = NULL;
410 add_object_array(o, name, &rev.pending);
411 ret = cmd_log_walk(&rev);
412 break;
413 default:
414 ret = error("Unknown type: %d", o->type);
417 free(objects);
418 return ret;
422 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
424 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
426 struct rev_info rev;
427 struct setup_revision_opt opt;
429 git_config(git_log_config, NULL);
431 if (diff_use_color_default == -1)
432 diff_use_color_default = git_use_color_default;
434 init_revisions(&rev, prefix);
435 init_reflog_walk(&rev.reflog_info);
436 rev.abbrev_commit = 1;
437 rev.verbose_header = 1;
438 memset(&opt, 0, sizeof(opt));
439 opt.def = "HEAD";
440 cmd_log_init(argc, argv, prefix, &rev, &opt);
443 * This means that we override whatever commit format the user gave
444 * on the cmd line. Sad, but cmd_log_init() currently doesn't
445 * allow us to set a different default.
447 rev.commit_format = CMIT_FMT_ONELINE;
448 rev.use_terminator = 1;
449 rev.always_show_header = 1;
452 * We get called through "git reflog", so unlike the other log
453 * routines, we need to set up our pager manually..
455 setup_pager();
457 return cmd_log_walk(&rev);
460 int cmd_log(int argc, const char **argv, const char *prefix)
462 struct rev_info rev;
463 struct setup_revision_opt opt;
465 git_config(git_log_config, NULL);
467 if (diff_use_color_default == -1)
468 diff_use_color_default = git_use_color_default;
470 init_revisions(&rev, prefix);
471 rev.always_show_header = 1;
472 memset(&opt, 0, sizeof(opt));
473 opt.def = "HEAD";
474 cmd_log_init(argc, argv, prefix, &rev, &opt);
475 return cmd_log_walk(&rev);
478 /* format-patch */
480 static const char *fmt_patch_suffix = ".patch";
481 static int numbered = 0;
482 static int auto_number = 1;
484 static char *default_attach = NULL;
486 static struct string_list extra_hdr;
487 static struct string_list extra_to;
488 static struct string_list extra_cc;
490 static void add_header(const char *value)
492 struct string_list_item *item;
493 int len = strlen(value);
494 while (len && value[len - 1] == '\n')
495 len--;
497 if (!strncasecmp(value, "to: ", 4)) {
498 item = string_list_append(value + 4, &extra_to);
499 len -= 4;
500 } else if (!strncasecmp(value, "cc: ", 4)) {
501 item = string_list_append(value + 4, &extra_cc);
502 len -= 4;
503 } else {
504 item = string_list_append(value, &extra_hdr);
507 item->string[len] = '\0';
510 #define THREAD_SHALLOW 1
511 #define THREAD_DEEP 2
512 static int thread = 0;
513 static int do_signoff = 0;
515 static int git_format_config(const char *var, const char *value, void *cb)
517 if (!strcmp(var, "format.headers")) {
518 if (!value)
519 die("format.headers without value");
520 add_header(value);
521 return 0;
523 if (!strcmp(var, "format.suffix"))
524 return git_config_string(&fmt_patch_suffix, var, value);
525 if (!strcmp(var, "format.to")) {
526 if (!value)
527 return config_error_nonbool(var);
528 string_list_append(value, &extra_to);
529 return 0;
531 if (!strcmp(var, "format.cc")) {
532 if (!value)
533 return config_error_nonbool(var);
534 string_list_append(value, &extra_cc);
535 return 0;
537 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
538 return 0;
540 if (!strcmp(var, "format.numbered")) {
541 if (value && !strcasecmp(value, "auto")) {
542 auto_number = 1;
543 return 0;
545 numbered = git_config_bool(var, value);
546 auto_number = auto_number && numbered;
547 return 0;
549 if (!strcmp(var, "format.attach")) {
550 if (value && *value)
551 default_attach = xstrdup(value);
552 else
553 default_attach = xstrdup(git_version_string);
554 return 0;
556 if (!strcmp(var, "format.thread")) {
557 if (value && !strcasecmp(value, "deep")) {
558 thread = THREAD_DEEP;
559 return 0;
561 if (value && !strcasecmp(value, "shallow")) {
562 thread = THREAD_SHALLOW;
563 return 0;
565 thread = git_config_bool(var, value) && THREAD_SHALLOW;
566 return 0;
568 if (!strcmp(var, "format.signoff")) {
569 do_signoff = git_config_bool(var, value);
570 return 0;
573 return git_log_config(var, value, cb);
576 static FILE *realstdout = NULL;
577 static const char *output_directory = NULL;
578 static int outdir_offset;
580 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
582 struct strbuf filename = STRBUF_INIT;
583 int suffix_len = strlen(fmt_patch_suffix) + 1;
585 if (output_directory) {
586 strbuf_addstr(&filename, output_directory);
587 if (filename.len >=
588 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
589 return error("name of output directory is too long");
590 if (filename.buf[filename.len - 1] != '/')
591 strbuf_addch(&filename, '/');
594 get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
596 if (!DIFF_OPT_TST(&rev->diffopt, QUICK))
597 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
599 if (freopen(filename.buf, "w", stdout) == NULL)
600 return error("Cannot open patch file %s", filename.buf);
602 strbuf_release(&filename);
603 return 0;
606 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
608 struct rev_info check_rev;
609 struct commit *commit;
610 struct object *o1, *o2;
611 unsigned flags1, flags2;
613 if (rev->pending.nr != 2)
614 die("Need exactly one range.");
616 o1 = rev->pending.objects[0].item;
617 flags1 = o1->flags;
618 o2 = rev->pending.objects[1].item;
619 flags2 = o2->flags;
621 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
622 die("Not a range.");
624 init_patch_ids(ids);
626 /* given a range a..b get all patch ids for b..a */
627 init_revisions(&check_rev, prefix);
628 o1->flags ^= UNINTERESTING;
629 o2->flags ^= UNINTERESTING;
630 add_pending_object(&check_rev, o1, "o1");
631 add_pending_object(&check_rev, o2, "o2");
632 if (prepare_revision_walk(&check_rev))
633 die("revision walk setup failed");
635 while ((commit = get_revision(&check_rev)) != NULL) {
636 /* ignore merges */
637 if (commit->parents && commit->parents->next)
638 continue;
640 add_commit_patch_id(commit, ids);
643 /* reset for next revision walk */
644 clear_commit_marks((struct commit *)o1,
645 SEEN | UNINTERESTING | SHOWN | ADDED);
646 clear_commit_marks((struct commit *)o2,
647 SEEN | UNINTERESTING | SHOWN | ADDED);
648 o1->flags = flags1;
649 o2->flags = flags2;
652 static void gen_message_id(struct rev_info *info, char *base)
654 const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
655 const char *email_start = strrchr(committer, '<');
656 const char *email_end = strrchr(committer, '>');
657 struct strbuf buf = STRBUF_INIT;
658 if (!email_start || !email_end || email_start > email_end - 1)
659 die("Could not extract email from committer identity.");
660 strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
661 (unsigned long) time(NULL),
662 (int)(email_end - email_start - 1), email_start + 1);
663 info->message_id = strbuf_detach(&buf, NULL);
666 static void make_cover_letter(struct rev_info *rev, int use_stdout,
667 int numbered, int numbered_files,
668 struct commit *origin,
669 int nr, struct commit **list, struct commit *head)
671 const char *committer;
672 const char *subject_start = NULL;
673 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
674 const char *msg;
675 const char *extra_headers = rev->extra_headers;
676 struct shortlog log;
677 struct strbuf sb = STRBUF_INIT;
678 int i;
679 const char *encoding = "UTF-8";
680 struct diff_options opts;
681 int need_8bit_cte = 0;
682 struct commit *commit = NULL;
684 if (rev->commit_format != CMIT_FMT_EMAIL)
685 die("Cover letter needs email format");
687 committer = git_committer_info(0);
689 if (!numbered_files) {
691 * We fake a commit for the cover letter so we get the filename
692 * desired.
694 commit = xcalloc(1, sizeof(*commit));
695 commit->buffer = xmalloc(400);
696 snprintf(commit->buffer, 400,
697 "tree 0000000000000000000000000000000000000000\n"
698 "parent %s\n"
699 "author %s\n"
700 "committer %s\n\n"
701 "cover letter\n",
702 sha1_to_hex(head->object.sha1), committer, committer);
705 if (!use_stdout && reopen_stdout(commit, rev))
706 return;
708 if (commit) {
710 free(commit->buffer);
711 free(commit);
714 log_write_email_headers(rev, head, &subject_start, &extra_headers,
715 &need_8bit_cte);
717 for (i = 0; !need_8bit_cte && i < nr; i++)
718 if (has_non_ascii(list[i]->buffer))
719 need_8bit_cte = 1;
721 msg = body;
722 pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
723 encoding);
724 pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
725 encoding, need_8bit_cte);
726 pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
727 printf("%s\n", sb.buf);
729 strbuf_release(&sb);
731 shortlog_init(&log);
732 log.wrap_lines = 1;
733 log.wrap = 72;
734 log.in1 = 2;
735 log.in2 = 4;
736 for (i = 0; i < nr; i++)
737 shortlog_add_commit(&log, list[i]);
739 shortlog_output(&log);
742 * We can only do diffstat with a unique reference point
744 if (!origin)
745 return;
747 memcpy(&opts, &rev->diffopt, sizeof(opts));
748 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
750 diff_setup_done(&opts);
752 diff_tree_sha1(origin->tree->object.sha1,
753 head->tree->object.sha1,
754 "", &opts);
755 diffcore_std(&opts);
756 diff_flush(&opts);
758 printf("\n");
761 static const char *clean_message_id(const char *msg_id)
763 char ch;
764 const char *a, *z, *m;
766 m = msg_id;
767 while ((ch = *m) && (isspace(ch) || (ch == '<')))
768 m++;
769 a = m;
770 z = NULL;
771 while ((ch = *m)) {
772 if (!isspace(ch) && (ch != '>'))
773 z = m;
774 m++;
776 if (!z)
777 die("insane in-reply-to: %s", msg_id);
778 if (++z == m)
779 return a;
780 return xmemdupz(a, z - a);
783 static const char *set_outdir(const char *prefix, const char *output_directory)
785 if (output_directory && is_absolute_path(output_directory))
786 return output_directory;
788 if (!prefix || !*prefix) {
789 if (output_directory)
790 return output_directory;
791 /* The user did not explicitly ask for "./" */
792 outdir_offset = 2;
793 return "./";
796 outdir_offset = strlen(prefix);
797 if (!output_directory)
798 return prefix;
800 return xstrdup(prefix_filename(prefix, outdir_offset,
801 output_directory));
804 static const char * const builtin_format_patch_usage[] = {
805 "git format-patch [options] [<since> | <revision range>]",
806 NULL
809 static int keep_subject = 0;
811 static int keep_callback(const struct option *opt, const char *arg, int unset)
813 ((struct rev_info *)opt->value)->total = -1;
814 keep_subject = 1;
815 return 0;
818 static int subject_prefix = 0;
820 static int subject_prefix_callback(const struct option *opt, const char *arg,
821 int unset)
823 subject_prefix = 1;
824 ((struct rev_info *)opt->value)->subject_prefix = arg;
825 return 0;
828 static int numbered_cmdline_opt = 0;
830 static int numbered_callback(const struct option *opt, const char *arg,
831 int unset)
833 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
834 if (unset)
835 auto_number = 0;
836 return 0;
839 static int no_numbered_callback(const struct option *opt, const char *arg,
840 int unset)
842 return numbered_callback(opt, arg, 1);
845 static int output_directory_callback(const struct option *opt, const char *arg,
846 int unset)
848 const char **dir = (const char **)opt->value;
849 if (*dir)
850 die("Two output directories?");
851 *dir = arg;
852 return 0;
855 static int thread_callback(const struct option *opt, const char *arg, int unset)
857 int *thread = (int *)opt->value;
858 if (unset)
859 *thread = 0;
860 else if (!arg || !strcmp(arg, "shallow"))
861 *thread = THREAD_SHALLOW;
862 else if (!strcmp(arg, "deep"))
863 *thread = THREAD_DEEP;
864 else
865 return 1;
866 return 0;
869 static int attach_callback(const struct option *opt, const char *arg, int unset)
871 struct rev_info *rev = (struct rev_info *)opt->value;
872 if (unset)
873 rev->mime_boundary = NULL;
874 else if (arg)
875 rev->mime_boundary = arg;
876 else
877 rev->mime_boundary = git_version_string;
878 rev->no_inline = unset ? 0 : 1;
879 return 0;
882 static int inline_callback(const struct option *opt, const char *arg, int unset)
884 struct rev_info *rev = (struct rev_info *)opt->value;
885 if (unset)
886 rev->mime_boundary = NULL;
887 else if (arg)
888 rev->mime_boundary = arg;
889 else
890 rev->mime_boundary = git_version_string;
891 rev->no_inline = 0;
892 return 0;
895 static int header_callback(const struct option *opt, const char *arg, int unset)
897 if (unset) {
898 string_list_clear(&extra_hdr, 0);
899 string_list_clear(&extra_to, 0);
900 string_list_clear(&extra_cc, 0);
901 } else {
902 add_header(arg);
904 return 0;
907 static int to_callback(const struct option *opt, const char *arg, int unset)
909 if (unset)
910 string_list_clear(&extra_to, 0);
911 else
912 string_list_append(arg, &extra_to);
913 return 0;
916 static int cc_callback(const struct option *opt, const char *arg, int unset)
918 if (unset)
919 string_list_clear(&extra_cc, 0);
920 else
921 string_list_append(arg, &extra_cc);
922 return 0;
925 int cmd_format_patch(int argc, const char **argv, const char *prefix)
927 struct commit *commit;
928 struct commit **list = NULL;
929 struct rev_info rev;
930 struct setup_revision_opt s_r_opt;
931 int nr = 0, total, i;
932 int use_stdout = 0;
933 int start_number = -1;
934 int numbered_files = 0; /* _just_ numbers */
935 int ignore_if_in_upstream = 0;
936 int cover_letter = 0;
937 int boundary_count = 0;
938 int no_binary_diff = 0;
939 struct commit *origin = NULL, *head = NULL;
940 const char *in_reply_to = NULL;
941 struct patch_ids ids;
942 char *add_signoff = NULL;
943 struct strbuf buf = STRBUF_INIT;
944 int use_patch_format = 0;
945 const struct option builtin_format_patch_options[] = {
946 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
947 "use [PATCH n/m] even with a single patch",
948 PARSE_OPT_NOARG, numbered_callback },
949 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
950 "use [PATCH] even with multiple patches",
951 PARSE_OPT_NOARG, no_numbered_callback },
952 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
953 OPT_BOOLEAN(0, "stdout", &use_stdout,
954 "print patches to standard out"),
955 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
956 "generate a cover letter"),
957 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
958 "use simple number sequence for output file names"),
959 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
960 "use <sfx> instead of '.patch'"),
961 OPT_INTEGER(0, "start-number", &start_number,
962 "start numbering patches at <n> instead of 1"),
963 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
964 "Use [<prefix>] instead of [PATCH]",
965 PARSE_OPT_NONEG, subject_prefix_callback },
966 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
967 "dir", "store resulting files in <dir>",
968 PARSE_OPT_NONEG, output_directory_callback },
969 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
970 "don't strip/add [PATCH]",
971 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
972 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
973 "don't output binary diffs"),
974 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
975 "don't include a patch matching a commit upstream"),
976 { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
977 "show patch format instead of default (patch + stat)",
978 PARSE_OPT_NONEG | PARSE_OPT_NOARG },
979 OPT_GROUP("Messaging"),
980 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
981 "add email header", 0, header_callback },
982 { OPTION_CALLBACK, 0, "to", NULL, "email", "add To: header",
983 0, to_callback },
984 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
985 0, cc_callback },
986 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
987 "make first mail a reply to <message-id>"),
988 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
989 "attach the patch", PARSE_OPT_OPTARG,
990 attach_callback },
991 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
992 "inline the patch",
993 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
994 inline_callback },
995 { OPTION_CALLBACK, 0, "thread", &thread, "style",
996 "enable message threading, styles: shallow, deep",
997 PARSE_OPT_OPTARG, thread_callback },
998 OPT_END()
1001 extra_hdr.strdup_strings = 1;
1002 extra_to.strdup_strings = 1;
1003 extra_cc.strdup_strings = 1;
1004 git_config(git_format_config, NULL);
1005 init_revisions(&rev, prefix);
1006 rev.commit_format = CMIT_FMT_EMAIL;
1007 rev.verbose_header = 1;
1008 rev.diff = 1;
1009 rev.combine_merges = 0;
1010 rev.ignore_merges = 1;
1011 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1012 rev.subject_prefix = fmt_patch_subject_prefix;
1013 memset(&s_r_opt, 0, sizeof(s_r_opt));
1014 s_r_opt.def = "HEAD";
1016 if (default_attach) {
1017 rev.mime_boundary = default_attach;
1018 rev.no_inline = 1;
1022 * Parse the arguments before setup_revisions(), or something
1023 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1024 * possibly a valid SHA1.
1026 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1027 builtin_format_patch_usage,
1028 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1029 PARSE_OPT_KEEP_DASHDASH);
1031 if (do_signoff) {
1032 const char *committer;
1033 const char *endpos;
1034 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
1035 endpos = strchr(committer, '>');
1036 if (!endpos)
1037 die("bogus committer info %s", committer);
1038 add_signoff = xmemdupz(committer, endpos - committer + 1);
1041 for (i = 0; i < extra_hdr.nr; i++) {
1042 strbuf_addstr(&buf, extra_hdr.items[i].string);
1043 strbuf_addch(&buf, '\n');
1046 if (extra_to.nr)
1047 strbuf_addstr(&buf, "To: ");
1048 for (i = 0; i < extra_to.nr; i++) {
1049 if (i)
1050 strbuf_addstr(&buf, " ");
1051 strbuf_addstr(&buf, extra_to.items[i].string);
1052 if (i + 1 < extra_to.nr)
1053 strbuf_addch(&buf, ',');
1054 strbuf_addch(&buf, '\n');
1057 if (extra_cc.nr)
1058 strbuf_addstr(&buf, "Cc: ");
1059 for (i = 0; i < extra_cc.nr; i++) {
1060 if (i)
1061 strbuf_addstr(&buf, " ");
1062 strbuf_addstr(&buf, extra_cc.items[i].string);
1063 if (i + 1 < extra_cc.nr)
1064 strbuf_addch(&buf, ',');
1065 strbuf_addch(&buf, '\n');
1068 rev.extra_headers = strbuf_detach(&buf, NULL);
1070 if (start_number < 0)
1071 start_number = 1;
1074 * If numbered is set solely due to format.numbered in config,
1075 * and it would conflict with --keep-subject (-k) from the
1076 * command line, reset "numbered".
1078 if (numbered && keep_subject && !numbered_cmdline_opt)
1079 numbered = 0;
1081 if (numbered && keep_subject)
1082 die ("-n and -k are mutually exclusive.");
1083 if (keep_subject && subject_prefix)
1084 die ("--subject-prefix and -k are mutually exclusive.");
1086 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1087 if (argc > 1)
1088 die ("unrecognized argument: %s", argv[1]);
1090 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1091 die("--name-only does not make sense");
1092 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1093 die("--name-status does not make sense");
1094 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1095 die("--check does not make sense");
1097 if (!use_patch_format &&
1098 (!rev.diffopt.output_format ||
1099 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1100 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1102 /* Always generate a patch */
1103 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1105 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1106 DIFF_OPT_SET(&rev.diffopt, BINARY);
1108 if (!use_stdout)
1109 output_directory = set_outdir(prefix, output_directory);
1111 if (output_directory) {
1112 if (use_stdout)
1113 die("standard output, or directory, which one?");
1114 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1115 die_errno("Could not create directory '%s'",
1116 output_directory);
1119 if (rev.pending.nr == 1) {
1120 if (rev.max_count < 0 && !rev.show_root_diff) {
1122 * This is traditional behaviour of "git format-patch
1123 * origin" that prepares what the origin side still
1124 * does not have.
1126 rev.pending.objects[0].item->flags |= UNINTERESTING;
1127 add_head_to_pending(&rev);
1130 * Otherwise, it is "format-patch -22 HEAD", and/or
1131 * "format-patch --root HEAD". The user wants
1132 * get_revision() to do the usual traversal.
1137 * We cannot move this anywhere earlier because we do want to
1138 * know if --root was given explicitly from the command line.
1140 rev.show_root_diff = 1;
1142 if (cover_letter) {
1143 /* remember the range */
1144 int i;
1145 for (i = 0; i < rev.pending.nr; i++) {
1146 struct object *o = rev.pending.objects[i].item;
1147 if (!(o->flags & UNINTERESTING))
1148 head = (struct commit *)o;
1150 /* We can't generate a cover letter without any patches */
1151 if (!head)
1152 return 0;
1155 if (ignore_if_in_upstream)
1156 get_patch_ids(&rev, &ids, prefix);
1158 if (!use_stdout)
1159 realstdout = xfdopen(xdup(1), "w");
1161 if (prepare_revision_walk(&rev))
1162 die("revision walk setup failed");
1163 rev.boundary = 1;
1164 while ((commit = get_revision(&rev)) != NULL) {
1165 if (commit->object.flags & BOUNDARY) {
1166 boundary_count++;
1167 origin = (boundary_count == 1) ? commit : NULL;
1168 continue;
1171 /* ignore merges */
1172 if (commit->parents && commit->parents->next)
1173 continue;
1175 if (ignore_if_in_upstream &&
1176 has_commit_patch_id(commit, &ids))
1177 continue;
1179 nr++;
1180 list = xrealloc(list, nr * sizeof(list[0]));
1181 list[nr - 1] = commit;
1183 total = nr;
1184 if (!keep_subject && auto_number && total > 1)
1185 numbered = 1;
1186 if (numbered)
1187 rev.total = total + start_number - 1;
1188 if (in_reply_to || thread || cover_letter)
1189 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1190 if (in_reply_to) {
1191 const char *msgid = clean_message_id(in_reply_to);
1192 string_list_append(msgid, rev.ref_message_ids);
1194 rev.numbered_files = numbered_files;
1195 rev.patch_suffix = fmt_patch_suffix;
1196 if (cover_letter) {
1197 if (thread)
1198 gen_message_id(&rev, "cover");
1199 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1200 origin, nr, list, head);
1201 total++;
1202 start_number--;
1204 rev.add_signoff = add_signoff;
1205 while (0 <= --nr) {
1206 int shown;
1207 commit = list[nr];
1208 rev.nr = total - nr + (start_number - 1);
1209 /* Make the second and subsequent mails replies to the first */
1210 if (thread) {
1211 /* Have we already had a message ID? */
1212 if (rev.message_id) {
1214 * For deep threading: make every mail
1215 * a reply to the previous one, no
1216 * matter what other options are set.
1218 * For shallow threading:
1220 * Without --cover-letter and
1221 * --in-reply-to, make every mail a
1222 * reply to the one before.
1224 * With --in-reply-to but no
1225 * --cover-letter, make every mail a
1226 * reply to the <reply-to>.
1228 * With --cover-letter, make every
1229 * mail but the cover letter a reply
1230 * to the cover letter. The cover
1231 * letter is a reply to the
1232 * --in-reply-to, if specified.
1234 if (thread == THREAD_SHALLOW
1235 && rev.ref_message_ids->nr > 0
1236 && (!cover_letter || rev.nr > 1))
1237 free(rev.message_id);
1238 else
1239 string_list_append(rev.message_id,
1240 rev.ref_message_ids);
1242 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1245 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1246 &rev))
1247 die("Failed to create output files");
1248 shown = log_tree_commit(&rev, commit);
1249 free(commit->buffer);
1250 commit->buffer = NULL;
1252 /* We put one extra blank line between formatted
1253 * patches and this flag is used by log-tree code
1254 * to see if it needs to emit a LF before showing
1255 * the log; when using one file per patch, we do
1256 * not want the extra blank line.
1258 if (!use_stdout)
1259 rev.shown_one = 0;
1260 if (shown) {
1261 if (rev.mime_boundary)
1262 printf("\n--%s%s--\n\n\n",
1263 mime_boundary_leader,
1264 rev.mime_boundary);
1265 else
1266 printf("-- \n%s\n\n", git_version_string);
1268 if (!use_stdout)
1269 fclose(stdout);
1271 free(list);
1272 string_list_clear(&extra_to, 0);
1273 string_list_clear(&extra_cc, 0);
1274 string_list_clear(&extra_hdr, 0);
1275 if (ignore_if_in_upstream)
1276 free_patch_ids(&ids);
1277 return 0;
1280 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1282 unsigned char sha1[20];
1283 if (get_sha1(arg, sha1) == 0) {
1284 struct commit *commit = lookup_commit_reference(sha1);
1285 if (commit) {
1286 commit->object.flags |= flags;
1287 add_pending_object(revs, &commit->object, arg);
1288 return 0;
1291 return -1;
1294 static const char cherry_usage[] =
1295 "git cherry [-v] [<upstream> [<head> [<limit>]]]";
1296 int cmd_cherry(int argc, const char **argv, const char *prefix)
1298 struct rev_info revs;
1299 struct patch_ids ids;
1300 struct commit *commit;
1301 struct commit_list *list = NULL;
1302 struct branch *current_branch;
1303 const char *upstream;
1304 const char *head = "HEAD";
1305 const char *limit = NULL;
1306 int verbose = 0;
1308 if (argc > 1 && !strcmp(argv[1], "-v")) {
1309 verbose = 1;
1310 argc--;
1311 argv++;
1314 if (argc > 1 && !strcmp(argv[1], "-h"))
1315 usage(cherry_usage);
1317 switch (argc) {
1318 case 4:
1319 limit = argv[3];
1320 /* FALLTHROUGH */
1321 case 3:
1322 head = argv[2];
1323 /* FALLTHROUGH */
1324 case 2:
1325 upstream = argv[1];
1326 break;
1327 default:
1328 current_branch = branch_get(NULL);
1329 if (!current_branch || !current_branch->merge
1330 || !current_branch->merge[0]
1331 || !current_branch->merge[0]->dst) {
1332 fprintf(stderr, "Could not find a tracked"
1333 " remote branch, please"
1334 " specify <upstream> manually.\n");
1335 usage(cherry_usage);
1338 upstream = current_branch->merge[0]->dst;
1341 init_revisions(&revs, prefix);
1342 revs.diff = 1;
1343 revs.combine_merges = 0;
1344 revs.ignore_merges = 1;
1345 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1347 if (add_pending_commit(head, &revs, 0))
1348 die("Unknown commit %s", head);
1349 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1350 die("Unknown commit %s", upstream);
1352 /* Don't say anything if head and upstream are the same. */
1353 if (revs.pending.nr == 2) {
1354 struct object_array_entry *o = revs.pending.objects;
1355 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1356 return 0;
1359 get_patch_ids(&revs, &ids, prefix);
1361 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1362 die("Unknown commit %s", limit);
1364 /* reverse the list of commits */
1365 if (prepare_revision_walk(&revs))
1366 die("revision walk setup failed");
1367 while ((commit = get_revision(&revs)) != NULL) {
1368 /* ignore merges */
1369 if (commit->parents && commit->parents->next)
1370 continue;
1372 commit_list_insert(commit, &list);
1375 while (list) {
1376 char sign = '+';
1378 commit = list->item;
1379 if (has_commit_patch_id(commit, &ids))
1380 sign = '-';
1382 if (verbose) {
1383 struct strbuf buf = STRBUF_INIT;
1384 struct pretty_print_context ctx = {0};
1385 pretty_print_commit(CMIT_FMT_ONELINE, commit,
1386 &buf, &ctx);
1387 printf("%c %s %s\n", sign,
1388 sha1_to_hex(commit->object.sha1), buf.buf);
1389 strbuf_release(&buf);
1391 else {
1392 printf("%c %s\n", sign,
1393 sha1_to_hex(commit->object.sha1));
1396 list = list->next;
1399 free_patch_ids(&ids);
1400 return 0;