git submodule foreach: Add --recursive to recurse into nested submodules
[git/gitweb.git] / builtin-log.c
blob82236c531bb3c70875285467cbd775fec27c939e
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)
37 int i;
39 rev->abbrev = DEFAULT_ABBREV;
40 rev->commit_format = CMIT_FMT_DEFAULT;
41 if (fmt_pretty)
42 get_commit_format(fmt_pretty, rev);
43 rev->verbose_header = 1;
44 DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
45 rev->show_root_diff = default_show_root;
46 rev->subject_prefix = fmt_patch_subject_prefix;
47 DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
49 if (default_date_mode)
50 rev->date_mode = parse_date_format(default_date_mode);
52 argc = setup_revisions(argc, argv, rev, "HEAD");
54 if (rev->diffopt.pickaxe || rev->diffopt.filter)
55 rev->always_show_header = 0;
56 if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
57 rev->always_show_header = 0;
58 if (rev->diffopt.nr_paths != 1)
59 usage("git logs can only follow renames on one pathname at a time");
61 for (i = 1; i < argc; i++) {
62 const char *arg = argv[i];
63 if (!strcmp(arg, "--decorate")) {
64 load_ref_decorations();
65 rev->show_decorations = 1;
66 } else if (!strcmp(arg, "--source")) {
67 rev->show_source = 1;
68 } else if (!strcmp(arg, "-h")) {
69 usage(builtin_log_usage);
70 } else
71 die("unrecognized argument: %s", arg);
76 * This gives a rough estimate for how many commits we
77 * will print out in the list.
79 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
81 int n = 0;
83 while (list) {
84 struct commit *commit = list->item;
85 unsigned int flags = commit->object.flags;
86 list = list->next;
87 if (!(flags & (TREESAME | UNINTERESTING)))
88 n++;
90 return n;
93 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
95 if (rev->shown_one) {
96 rev->shown_one = 0;
97 if (rev->commit_format != CMIT_FMT_ONELINE)
98 putchar(rev->diffopt.line_termination);
100 printf("Final output: %d %s\n", nr, stage);
103 static struct itimerval early_output_timer;
105 static void log_show_early(struct rev_info *revs, struct commit_list *list)
107 int i = revs->early_output;
108 int show_header = 1;
110 sort_in_topological_order(&list, revs->lifo);
111 while (list && i) {
112 struct commit *commit = list->item;
113 switch (simplify_commit(revs, commit)) {
114 case commit_show:
115 if (show_header) {
116 int n = estimate_commit_count(revs, list);
117 show_early_header(revs, "incomplete", n);
118 show_header = 0;
120 log_tree_commit(revs, commit);
121 i--;
122 break;
123 case commit_ignore:
124 break;
125 case commit_error:
126 return;
128 list = list->next;
131 /* Did we already get enough commits for the early output? */
132 if (!i)
133 return;
136 * ..if no, then repeat it twice a second until we
137 * do.
139 * NOTE! We don't use "it_interval", because if the
140 * reader isn't listening, we want our output to be
141 * throttled by the writing, and not have the timer
142 * trigger every second even if we're blocked on a
143 * reader!
145 early_output_timer.it_value.tv_sec = 0;
146 early_output_timer.it_value.tv_usec = 500000;
147 setitimer(ITIMER_REAL, &early_output_timer, NULL);
150 static void early_output(int signal)
152 show_early_output = log_show_early;
155 static void setup_early_output(struct rev_info *rev)
157 struct sigaction sa;
160 * Set up the signal handler, minimally intrusively:
161 * we only set a single volatile integer word (not
162 * using sigatomic_t - trying to avoid unnecessary
163 * system dependencies and headers), and using
164 * SA_RESTART.
166 memset(&sa, 0, sizeof(sa));
167 sa.sa_handler = early_output;
168 sigemptyset(&sa.sa_mask);
169 sa.sa_flags = SA_RESTART;
170 sigaction(SIGALRM, &sa, NULL);
173 * If we can get the whole output in less than a
174 * tenth of a second, don't even bother doing the
175 * early-output thing..
177 * This is a one-time-only trigger.
179 early_output_timer.it_value.tv_sec = 0;
180 early_output_timer.it_value.tv_usec = 100000;
181 setitimer(ITIMER_REAL, &early_output_timer, NULL);
184 static void finish_early_output(struct rev_info *rev)
186 int n = estimate_commit_count(rev, rev->commits);
187 signal(SIGALRM, SIG_IGN);
188 show_early_header(rev, "done", n);
191 static int cmd_log_walk(struct rev_info *rev)
193 struct commit *commit;
195 if (rev->early_output)
196 setup_early_output(rev);
198 if (prepare_revision_walk(rev))
199 die("revision walk setup failed");
201 if (rev->early_output)
202 finish_early_output(rev);
205 * For --check and --exit-code, the exit code is based on CHECK_FAILED
206 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
207 * retain that state information if replacing rev->diffopt in this loop
209 while ((commit = get_revision(rev)) != NULL) {
210 log_tree_commit(rev, commit);
211 if (!rev->reflog_info) {
212 /* we allow cycles in reflog ancestry */
213 free(commit->buffer);
214 commit->buffer = NULL;
216 free_commit_list(commit->parents);
217 commit->parents = NULL;
219 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
220 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
221 return 02;
223 return diff_result_code(&rev->diffopt, 0);
226 static int git_log_config(const char *var, const char *value, void *cb)
228 if (!strcmp(var, "format.pretty"))
229 return git_config_string(&fmt_pretty, var, value);
230 if (!strcmp(var, "format.subjectprefix"))
231 return git_config_string(&fmt_patch_subject_prefix, var, value);
232 if (!strcmp(var, "log.date"))
233 return git_config_string(&default_date_mode, var, value);
234 if (!strcmp(var, "log.showroot")) {
235 default_show_root = git_config_bool(var, value);
236 return 0;
238 return git_diff_ui_config(var, value, cb);
241 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
243 struct rev_info rev;
245 git_config(git_log_config, NULL);
247 if (diff_use_color_default == -1)
248 diff_use_color_default = git_use_color_default;
250 init_revisions(&rev, prefix);
251 rev.diff = 1;
252 rev.simplify_history = 0;
253 cmd_log_init(argc, argv, prefix, &rev);
254 if (!rev.diffopt.output_format)
255 rev.diffopt.output_format = DIFF_FORMAT_RAW;
256 return cmd_log_walk(&rev);
259 static void show_tagger(char *buf, int len, struct rev_info *rev)
261 struct strbuf out = STRBUF_INIT;
263 pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
264 git_log_output_encoding ?
265 git_log_output_encoding: git_commit_encoding);
266 printf("%s", out.buf);
267 strbuf_release(&out);
270 static int show_object(const unsigned char *sha1, int show_tag_object,
271 struct rev_info *rev)
273 unsigned long size;
274 enum object_type type;
275 char *buf = read_sha1_file(sha1, &type, &size);
276 int offset = 0;
278 if (!buf)
279 return error("Could not read object %s", sha1_to_hex(sha1));
281 if (show_tag_object)
282 while (offset < size && buf[offset] != '\n') {
283 int new_offset = offset + 1;
284 while (new_offset < size && buf[new_offset++] != '\n')
285 ; /* do nothing */
286 if (!prefixcmp(buf + offset, "tagger "))
287 show_tagger(buf + offset + 7,
288 new_offset - offset - 7, rev);
289 offset = new_offset;
292 if (offset < size)
293 fwrite(buf + offset, size - offset, 1, stdout);
294 free(buf);
295 return 0;
298 static int show_tree_object(const unsigned char *sha1,
299 const char *base, int baselen,
300 const char *pathname, unsigned mode, int stage, void *context)
302 printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
303 return 0;
306 int cmd_show(int argc, const char **argv, const char *prefix)
308 struct rev_info rev;
309 struct object_array_entry *objects;
310 int i, count, ret = 0;
312 git_config(git_log_config, NULL);
314 if (diff_use_color_default == -1)
315 diff_use_color_default = git_use_color_default;
317 init_revisions(&rev, prefix);
318 rev.diff = 1;
319 rev.combine_merges = 1;
320 rev.dense_combined_merges = 1;
321 rev.always_show_header = 1;
322 rev.ignore_merges = 0;
323 rev.no_walk = 1;
324 cmd_log_init(argc, argv, prefix, &rev);
326 count = rev.pending.nr;
327 objects = rev.pending.objects;
328 for (i = 0; i < count && !ret; i++) {
329 struct object *o = objects[i].item;
330 const char *name = objects[i].name;
331 switch (o->type) {
332 case OBJ_BLOB:
333 ret = show_object(o->sha1, 0, NULL);
334 break;
335 case OBJ_TAG: {
336 struct tag *t = (struct tag *)o;
338 if (rev.shown_one)
339 putchar('\n');
340 printf("%stag %s%s\n",
341 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
342 t->tag,
343 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
344 ret = show_object(o->sha1, 1, &rev);
345 rev.shown_one = 1;
346 if (ret)
347 break;
348 o = parse_object(t->tagged->sha1);
349 if (!o)
350 ret = error("Could not read object %s",
351 sha1_to_hex(t->tagged->sha1));
352 objects[i].item = o;
353 i--;
354 break;
356 case OBJ_TREE:
357 if (rev.shown_one)
358 putchar('\n');
359 printf("%stree %s%s\n\n",
360 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
361 name,
362 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
363 read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
364 show_tree_object, NULL);
365 rev.shown_one = 1;
366 break;
367 case OBJ_COMMIT:
368 rev.pending.nr = rev.pending.alloc = 0;
369 rev.pending.objects = NULL;
370 add_object_array(o, name, &rev.pending);
371 ret = cmd_log_walk(&rev);
372 break;
373 default:
374 ret = error("Unknown type: %d", o->type);
377 free(objects);
378 return ret;
382 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
384 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
386 struct rev_info rev;
388 git_config(git_log_config, NULL);
390 if (diff_use_color_default == -1)
391 diff_use_color_default = git_use_color_default;
393 init_revisions(&rev, prefix);
394 init_reflog_walk(&rev.reflog_info);
395 rev.abbrev_commit = 1;
396 rev.verbose_header = 1;
397 cmd_log_init(argc, argv, prefix, &rev);
400 * This means that we override whatever commit format the user gave
401 * on the cmd line. Sad, but cmd_log_init() currently doesn't
402 * allow us to set a different default.
404 rev.commit_format = CMIT_FMT_ONELINE;
405 rev.use_terminator = 1;
406 rev.always_show_header = 1;
409 * We get called through "git reflog", so unlike the other log
410 * routines, we need to set up our pager manually..
412 setup_pager();
414 return cmd_log_walk(&rev);
417 int cmd_log(int argc, const char **argv, const char *prefix)
419 struct rev_info rev;
421 git_config(git_log_config, NULL);
423 if (diff_use_color_default == -1)
424 diff_use_color_default = git_use_color_default;
426 init_revisions(&rev, prefix);
427 rev.always_show_header = 1;
428 cmd_log_init(argc, argv, prefix, &rev);
429 return cmd_log_walk(&rev);
432 /* format-patch */
434 static const char *fmt_patch_suffix = ".patch";
435 static int numbered = 0;
436 static int auto_number = 1;
438 static char *default_attach = NULL;
440 static char **extra_hdr;
441 static int extra_hdr_nr;
442 static int extra_hdr_alloc;
444 static char **extra_to;
445 static int extra_to_nr;
446 static int extra_to_alloc;
448 static char **extra_cc;
449 static int extra_cc_nr;
450 static int extra_cc_alloc;
452 static void add_header(const char *value)
454 int len = strlen(value);
455 while (len && value[len - 1] == '\n')
456 len--;
457 if (!strncasecmp(value, "to: ", 4)) {
458 ALLOC_GROW(extra_to, extra_to_nr + 1, extra_to_alloc);
459 extra_to[extra_to_nr++] = xstrndup(value + 4, len - 4);
460 return;
462 if (!strncasecmp(value, "cc: ", 4)) {
463 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
464 extra_cc[extra_cc_nr++] = xstrndup(value + 4, len - 4);
465 return;
467 ALLOC_GROW(extra_hdr, extra_hdr_nr + 1, extra_hdr_alloc);
468 extra_hdr[extra_hdr_nr++] = xstrndup(value, len);
471 #define THREAD_SHALLOW 1
472 #define THREAD_DEEP 2
473 static int thread = 0;
474 static int do_signoff = 0;
476 static int git_format_config(const char *var, const char *value, void *cb)
478 if (!strcmp(var, "format.headers")) {
479 if (!value)
480 die("format.headers without value");
481 add_header(value);
482 return 0;
484 if (!strcmp(var, "format.suffix"))
485 return git_config_string(&fmt_patch_suffix, var, value);
486 if (!strcmp(var, "format.cc")) {
487 if (!value)
488 return config_error_nonbool(var);
489 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
490 extra_cc[extra_cc_nr++] = xstrdup(value);
491 return 0;
493 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
494 return 0;
496 if (!strcmp(var, "format.numbered")) {
497 if (value && !strcasecmp(value, "auto")) {
498 auto_number = 1;
499 return 0;
501 numbered = git_config_bool(var, value);
502 auto_number = auto_number && numbered;
503 return 0;
505 if (!strcmp(var, "format.attach")) {
506 if (value && *value)
507 default_attach = xstrdup(value);
508 else
509 default_attach = xstrdup(git_version_string);
510 return 0;
512 if (!strcmp(var, "format.thread")) {
513 if (value && !strcasecmp(value, "deep")) {
514 thread = THREAD_DEEP;
515 return 0;
517 if (value && !strcasecmp(value, "shallow")) {
518 thread = THREAD_SHALLOW;
519 return 0;
521 thread = git_config_bool(var, value) && THREAD_SHALLOW;
522 return 0;
524 if (!strcmp(var, "format.signoff")) {
525 do_signoff = git_config_bool(var, value);
526 return 0;
529 return git_log_config(var, value, cb);
532 static FILE *realstdout = NULL;
533 static const char *output_directory = NULL;
534 static int outdir_offset;
536 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
538 struct strbuf filename = STRBUF_INIT;
539 int suffix_len = strlen(fmt_patch_suffix) + 1;
541 if (output_directory) {
542 strbuf_addstr(&filename, output_directory);
543 if (filename.len >=
544 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
545 return error("name of output directory is too long");
546 if (filename.buf[filename.len - 1] != '/')
547 strbuf_addch(&filename, '/');
550 get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
552 if (!DIFF_OPT_TST(&rev->diffopt, QUIET))
553 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
555 if (freopen(filename.buf, "w", stdout) == NULL)
556 return error("Cannot open patch file %s", filename.buf);
558 strbuf_release(&filename);
559 return 0;
562 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
564 struct rev_info check_rev;
565 struct commit *commit;
566 struct object *o1, *o2;
567 unsigned flags1, flags2;
569 if (rev->pending.nr != 2)
570 die("Need exactly one range.");
572 o1 = rev->pending.objects[0].item;
573 flags1 = o1->flags;
574 o2 = rev->pending.objects[1].item;
575 flags2 = o2->flags;
577 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
578 die("Not a range.");
580 init_patch_ids(ids);
582 /* given a range a..b get all patch ids for b..a */
583 init_revisions(&check_rev, prefix);
584 o1->flags ^= UNINTERESTING;
585 o2->flags ^= UNINTERESTING;
586 add_pending_object(&check_rev, o1, "o1");
587 add_pending_object(&check_rev, o2, "o2");
588 if (prepare_revision_walk(&check_rev))
589 die("revision walk setup failed");
591 while ((commit = get_revision(&check_rev)) != NULL) {
592 /* ignore merges */
593 if (commit->parents && commit->parents->next)
594 continue;
596 add_commit_patch_id(commit, ids);
599 /* reset for next revision walk */
600 clear_commit_marks((struct commit *)o1,
601 SEEN | UNINTERESTING | SHOWN | ADDED);
602 clear_commit_marks((struct commit *)o2,
603 SEEN | UNINTERESTING | SHOWN | ADDED);
604 o1->flags = flags1;
605 o2->flags = flags2;
608 static void gen_message_id(struct rev_info *info, char *base)
610 const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
611 const char *email_start = strrchr(committer, '<');
612 const char *email_end = strrchr(committer, '>');
613 struct strbuf buf = STRBUF_INIT;
614 if (!email_start || !email_end || email_start > email_end - 1)
615 die("Could not extract email from committer identity.");
616 strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
617 (unsigned long) time(NULL),
618 (int)(email_end - email_start - 1), email_start + 1);
619 info->message_id = strbuf_detach(&buf, NULL);
622 static void make_cover_letter(struct rev_info *rev, int use_stdout,
623 int numbered, int numbered_files,
624 struct commit *origin,
625 int nr, struct commit **list, struct commit *head)
627 const char *committer;
628 const char *subject_start = NULL;
629 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
630 const char *msg;
631 const char *extra_headers = rev->extra_headers;
632 struct shortlog log;
633 struct strbuf sb = STRBUF_INIT;
634 int i;
635 const char *encoding = "UTF-8";
636 struct diff_options opts;
637 int need_8bit_cte = 0;
638 struct commit *commit = NULL;
640 if (rev->commit_format != CMIT_FMT_EMAIL)
641 die("Cover letter needs email format");
643 committer = git_committer_info(0);
645 if (!numbered_files) {
647 * We fake a commit for the cover letter so we get the filename
648 * desired.
650 commit = xcalloc(1, sizeof(*commit));
651 commit->buffer = xmalloc(400);
652 snprintf(commit->buffer, 400,
653 "tree 0000000000000000000000000000000000000000\n"
654 "parent %s\n"
655 "author %s\n"
656 "committer %s\n\n"
657 "cover letter\n",
658 sha1_to_hex(head->object.sha1), committer, committer);
661 if (!use_stdout && reopen_stdout(commit, rev))
662 return;
664 if (commit) {
666 free(commit->buffer);
667 free(commit);
670 log_write_email_headers(rev, head, &subject_start, &extra_headers,
671 &need_8bit_cte);
673 for (i = 0; !need_8bit_cte && i < nr; i++)
674 if (has_non_ascii(list[i]->buffer))
675 need_8bit_cte = 1;
677 msg = body;
678 pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
679 encoding);
680 pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
681 encoding, need_8bit_cte);
682 pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
683 printf("%s\n", sb.buf);
685 strbuf_release(&sb);
687 shortlog_init(&log);
688 log.wrap_lines = 1;
689 log.wrap = 72;
690 log.in1 = 2;
691 log.in2 = 4;
692 for (i = 0; i < nr; i++)
693 shortlog_add_commit(&log, list[i]);
695 shortlog_output(&log);
698 * We can only do diffstat with a unique reference point
700 if (!origin)
701 return;
703 memcpy(&opts, &rev->diffopt, sizeof(opts));
704 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
706 diff_setup_done(&opts);
708 diff_tree_sha1(origin->tree->object.sha1,
709 head->tree->object.sha1,
710 "", &opts);
711 diffcore_std(&opts);
712 diff_flush(&opts);
714 printf("\n");
717 static const char *clean_message_id(const char *msg_id)
719 char ch;
720 const char *a, *z, *m;
722 m = msg_id;
723 while ((ch = *m) && (isspace(ch) || (ch == '<')))
724 m++;
725 a = m;
726 z = NULL;
727 while ((ch = *m)) {
728 if (!isspace(ch) && (ch != '>'))
729 z = m;
730 m++;
732 if (!z)
733 die("insane in-reply-to: %s", msg_id);
734 if (++z == m)
735 return a;
736 return xmemdupz(a, z - a);
739 static const char *set_outdir(const char *prefix, const char *output_directory)
741 if (output_directory && is_absolute_path(output_directory))
742 return output_directory;
744 if (!prefix || !*prefix) {
745 if (output_directory)
746 return output_directory;
747 /* The user did not explicitly ask for "./" */
748 outdir_offset = 2;
749 return "./";
752 outdir_offset = strlen(prefix);
753 if (!output_directory)
754 return prefix;
756 return xstrdup(prefix_filename(prefix, outdir_offset,
757 output_directory));
760 static const char * const builtin_format_patch_usage[] = {
761 "git format-patch [options] [<since> | <revision range>]",
762 NULL
765 static int keep_subject = 0;
767 static int keep_callback(const struct option *opt, const char *arg, int unset)
769 ((struct rev_info *)opt->value)->total = -1;
770 keep_subject = 1;
771 return 0;
774 static int subject_prefix = 0;
776 static int subject_prefix_callback(const struct option *opt, const char *arg,
777 int unset)
779 subject_prefix = 1;
780 ((struct rev_info *)opt->value)->subject_prefix = arg;
781 return 0;
784 static int numbered_cmdline_opt = 0;
786 static int numbered_callback(const struct option *opt, const char *arg,
787 int unset)
789 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
790 if (unset)
791 auto_number = 0;
792 return 0;
795 static int no_numbered_callback(const struct option *opt, const char *arg,
796 int unset)
798 return numbered_callback(opt, arg, 1);
801 static int output_directory_callback(const struct option *opt, const char *arg,
802 int unset)
804 const char **dir = (const char **)opt->value;
805 if (*dir)
806 die("Two output directories?");
807 *dir = arg;
808 return 0;
811 static int thread_callback(const struct option *opt, const char *arg, int unset)
813 int *thread = (int *)opt->value;
814 if (unset)
815 *thread = 0;
816 else if (!arg || !strcmp(arg, "shallow"))
817 *thread = THREAD_SHALLOW;
818 else if (!strcmp(arg, "deep"))
819 *thread = THREAD_DEEP;
820 else
821 return 1;
822 return 0;
825 static int attach_callback(const struct option *opt, const char *arg, int unset)
827 struct rev_info *rev = (struct rev_info *)opt->value;
828 if (unset)
829 rev->mime_boundary = NULL;
830 else if (arg)
831 rev->mime_boundary = arg;
832 else
833 rev->mime_boundary = git_version_string;
834 rev->no_inline = unset ? 0 : 1;
835 return 0;
838 static int inline_callback(const struct option *opt, const char *arg, int unset)
840 struct rev_info *rev = (struct rev_info *)opt->value;
841 if (unset)
842 rev->mime_boundary = NULL;
843 else if (arg)
844 rev->mime_boundary = arg;
845 else
846 rev->mime_boundary = git_version_string;
847 rev->no_inline = 0;
848 return 0;
851 static int header_callback(const struct option *opt, const char *arg, int unset)
853 add_header(arg);
854 return 0;
857 static int cc_callback(const struct option *opt, const char *arg, int unset)
859 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
860 extra_cc[extra_cc_nr++] = xstrdup(arg);
861 return 0;
864 int cmd_format_patch(int argc, const char **argv, const char *prefix)
866 struct commit *commit;
867 struct commit **list = NULL;
868 struct rev_info rev;
869 int nr = 0, total, i;
870 int use_stdout = 0;
871 int start_number = -1;
872 int numbered_files = 0; /* _just_ numbers */
873 int ignore_if_in_upstream = 0;
874 int cover_letter = 0;
875 int boundary_count = 0;
876 int no_binary_diff = 0;
877 struct commit *origin = NULL, *head = NULL;
878 const char *in_reply_to = NULL;
879 struct patch_ids ids;
880 char *add_signoff = NULL;
881 struct strbuf buf = STRBUF_INIT;
882 const struct option builtin_format_patch_options[] = {
883 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
884 "use [PATCH n/m] even with a single patch",
885 PARSE_OPT_NOARG, numbered_callback },
886 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
887 "use [PATCH] even with multiple patches",
888 PARSE_OPT_NOARG, no_numbered_callback },
889 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
890 OPT_BOOLEAN(0, "stdout", &use_stdout,
891 "print patches to standard out"),
892 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
893 "generate a cover letter"),
894 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
895 "use simple number sequence for output file names"),
896 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
897 "use <sfx> instead of '.patch'"),
898 OPT_INTEGER(0, "start-number", &start_number,
899 "start numbering patches at <n> instead of 1"),
900 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
901 "Use [<prefix>] instead of [PATCH]",
902 PARSE_OPT_NONEG, subject_prefix_callback },
903 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
904 "dir", "store resulting files in <dir>",
905 PARSE_OPT_NONEG, output_directory_callback },
906 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
907 "don't strip/add [PATCH]",
908 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
909 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
910 "don't output binary diffs"),
911 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
912 "don't include a patch matching a commit upstream"),
913 OPT_GROUP("Messaging"),
914 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
915 "add email header", PARSE_OPT_NONEG,
916 header_callback },
917 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
918 PARSE_OPT_NONEG, cc_callback },
919 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
920 "make first mail a reply to <message-id>"),
921 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
922 "attach the patch", PARSE_OPT_OPTARG,
923 attach_callback },
924 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
925 "inline the patch",
926 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
927 inline_callback },
928 { OPTION_CALLBACK, 0, "thread", &thread, "style",
929 "enable message threading, styles: shallow, deep",
930 PARSE_OPT_OPTARG, thread_callback },
931 OPT_END()
934 git_config(git_format_config, NULL);
935 init_revisions(&rev, prefix);
936 rev.commit_format = CMIT_FMT_EMAIL;
937 rev.verbose_header = 1;
938 rev.diff = 1;
939 rev.combine_merges = 0;
940 rev.ignore_merges = 1;
941 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
943 rev.subject_prefix = fmt_patch_subject_prefix;
945 if (default_attach) {
946 rev.mime_boundary = default_attach;
947 rev.no_inline = 1;
951 * Parse the arguments before setup_revisions(), or something
952 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
953 * possibly a valid SHA1.
955 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
956 builtin_format_patch_usage,
957 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN);
959 if (do_signoff) {
960 const char *committer;
961 const char *endpos;
962 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
963 endpos = strchr(committer, '>');
964 if (!endpos)
965 die("bogus committer info %s", committer);
966 add_signoff = xmemdupz(committer, endpos - committer + 1);
969 for (i = 0; i < extra_hdr_nr; i++) {
970 strbuf_addstr(&buf, extra_hdr[i]);
971 strbuf_addch(&buf, '\n');
974 if (extra_to_nr)
975 strbuf_addstr(&buf, "To: ");
976 for (i = 0; i < extra_to_nr; i++) {
977 if (i)
978 strbuf_addstr(&buf, " ");
979 strbuf_addstr(&buf, extra_to[i]);
980 if (i + 1 < extra_to_nr)
981 strbuf_addch(&buf, ',');
982 strbuf_addch(&buf, '\n');
985 if (extra_cc_nr)
986 strbuf_addstr(&buf, "Cc: ");
987 for (i = 0; i < extra_cc_nr; i++) {
988 if (i)
989 strbuf_addstr(&buf, " ");
990 strbuf_addstr(&buf, extra_cc[i]);
991 if (i + 1 < extra_cc_nr)
992 strbuf_addch(&buf, ',');
993 strbuf_addch(&buf, '\n');
996 rev.extra_headers = strbuf_detach(&buf, NULL);
998 if (start_number < 0)
999 start_number = 1;
1002 * If numbered is set solely due to format.numbered in config,
1003 * and it would conflict with --keep-subject (-k) from the
1004 * command line, reset "numbered".
1006 if (numbered && keep_subject && !numbered_cmdline_opt)
1007 numbered = 0;
1009 if (numbered && keep_subject)
1010 die ("-n and -k are mutually exclusive.");
1011 if (keep_subject && subject_prefix)
1012 die ("--subject-prefix and -k are mutually exclusive.");
1014 argc = setup_revisions(argc, argv, &rev, "HEAD");
1015 if (argc > 1)
1016 die ("unrecognized argument: %s", argv[1]);
1018 if (!rev.diffopt.output_format
1019 || rev.diffopt.output_format == DIFF_FORMAT_PATCH)
1020 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
1022 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1023 DIFF_OPT_SET(&rev.diffopt, BINARY);
1025 if (!use_stdout)
1026 output_directory = set_outdir(prefix, output_directory);
1028 if (output_directory) {
1029 if (use_stdout)
1030 die("standard output, or directory, which one?");
1031 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1032 die_errno("Could not create directory '%s'",
1033 output_directory);
1036 if (rev.pending.nr == 1) {
1037 if (rev.max_count < 0 && !rev.show_root_diff) {
1039 * This is traditional behaviour of "git format-patch
1040 * origin" that prepares what the origin side still
1041 * does not have.
1043 rev.pending.objects[0].item->flags |= UNINTERESTING;
1044 add_head_to_pending(&rev);
1047 * Otherwise, it is "format-patch -22 HEAD", and/or
1048 * "format-patch --root HEAD". The user wants
1049 * get_revision() to do the usual traversal.
1054 * We cannot move this anywhere earlier because we do want to
1055 * know if --root was given explicitly from the comand line.
1057 rev.show_root_diff = 1;
1059 if (cover_letter) {
1060 /* remember the range */
1061 int i;
1062 for (i = 0; i < rev.pending.nr; i++) {
1063 struct object *o = rev.pending.objects[i].item;
1064 if (!(o->flags & UNINTERESTING))
1065 head = (struct commit *)o;
1067 /* We can't generate a cover letter without any patches */
1068 if (!head)
1069 return 0;
1072 if (ignore_if_in_upstream)
1073 get_patch_ids(&rev, &ids, prefix);
1075 if (!use_stdout)
1076 realstdout = xfdopen(xdup(1), "w");
1078 if (prepare_revision_walk(&rev))
1079 die("revision walk setup failed");
1080 rev.boundary = 1;
1081 while ((commit = get_revision(&rev)) != NULL) {
1082 if (commit->object.flags & BOUNDARY) {
1083 boundary_count++;
1084 origin = (boundary_count == 1) ? commit : NULL;
1085 continue;
1088 /* ignore merges */
1089 if (commit->parents && commit->parents->next)
1090 continue;
1092 if (ignore_if_in_upstream &&
1093 has_commit_patch_id(commit, &ids))
1094 continue;
1096 nr++;
1097 list = xrealloc(list, nr * sizeof(list[0]));
1098 list[nr - 1] = commit;
1100 total = nr;
1101 if (!keep_subject && auto_number && total > 1)
1102 numbered = 1;
1103 if (numbered)
1104 rev.total = total + start_number - 1;
1105 if (in_reply_to || thread || cover_letter)
1106 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1107 if (in_reply_to) {
1108 const char *msgid = clean_message_id(in_reply_to);
1109 string_list_append(msgid, rev.ref_message_ids);
1111 rev.numbered_files = numbered_files;
1112 rev.patch_suffix = fmt_patch_suffix;
1113 if (cover_letter) {
1114 if (thread)
1115 gen_message_id(&rev, "cover");
1116 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1117 origin, nr, list, head);
1118 total++;
1119 start_number--;
1121 rev.add_signoff = add_signoff;
1122 while (0 <= --nr) {
1123 int shown;
1124 commit = list[nr];
1125 rev.nr = total - nr + (start_number - 1);
1126 /* Make the second and subsequent mails replies to the first */
1127 if (thread) {
1128 /* Have we already had a message ID? */
1129 if (rev.message_id) {
1131 * For deep threading: make every mail
1132 * a reply to the previous one, no
1133 * matter what other options are set.
1135 * For shallow threading:
1137 * Without --cover-letter and
1138 * --in-reply-to, make every mail a
1139 * reply to the one before.
1141 * With --in-reply-to but no
1142 * --cover-letter, make every mail a
1143 * reply to the <reply-to>.
1145 * With --cover-letter, make every
1146 * mail but the cover letter a reply
1147 * to the cover letter. The cover
1148 * letter is a reply to the
1149 * --in-reply-to, if specified.
1151 if (thread == THREAD_SHALLOW
1152 && rev.ref_message_ids->nr > 0
1153 && (!cover_letter || rev.nr > 1))
1154 free(rev.message_id);
1155 else
1156 string_list_append(rev.message_id,
1157 rev.ref_message_ids);
1159 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1162 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1163 &rev))
1164 die("Failed to create output files");
1165 shown = log_tree_commit(&rev, commit);
1166 free(commit->buffer);
1167 commit->buffer = NULL;
1169 /* We put one extra blank line between formatted
1170 * patches and this flag is used by log-tree code
1171 * to see if it needs to emit a LF before showing
1172 * the log; when using one file per patch, we do
1173 * not want the extra blank line.
1175 if (!use_stdout)
1176 rev.shown_one = 0;
1177 if (shown) {
1178 if (rev.mime_boundary)
1179 printf("\n--%s%s--\n\n\n",
1180 mime_boundary_leader,
1181 rev.mime_boundary);
1182 else
1183 printf("-- \n%s\n\n", git_version_string);
1185 if (!use_stdout)
1186 fclose(stdout);
1188 free(list);
1189 if (ignore_if_in_upstream)
1190 free_patch_ids(&ids);
1191 return 0;
1194 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1196 unsigned char sha1[20];
1197 if (get_sha1(arg, sha1) == 0) {
1198 struct commit *commit = lookup_commit_reference(sha1);
1199 if (commit) {
1200 commit->object.flags |= flags;
1201 add_pending_object(revs, &commit->object, arg);
1202 return 0;
1205 return -1;
1208 static const char cherry_usage[] =
1209 "git cherry [-v] [<upstream> [<head> [<limit>]]]";
1210 int cmd_cherry(int argc, const char **argv, const char *prefix)
1212 struct rev_info revs;
1213 struct patch_ids ids;
1214 struct commit *commit;
1215 struct commit_list *list = NULL;
1216 struct branch *current_branch;
1217 const char *upstream;
1218 const char *head = "HEAD";
1219 const char *limit = NULL;
1220 int verbose = 0;
1222 if (argc > 1 && !strcmp(argv[1], "-v")) {
1223 verbose = 1;
1224 argc--;
1225 argv++;
1228 switch (argc) {
1229 case 4:
1230 limit = argv[3];
1231 /* FALLTHROUGH */
1232 case 3:
1233 head = argv[2];
1234 /* FALLTHROUGH */
1235 case 2:
1236 upstream = argv[1];
1237 break;
1238 default:
1239 current_branch = branch_get(NULL);
1240 if (!current_branch || !current_branch->merge
1241 || !current_branch->merge[0]
1242 || !current_branch->merge[0]->dst) {
1243 fprintf(stderr, "Could not find a tracked"
1244 " remote branch, please"
1245 " specify <upstream> manually.\n");
1246 usage(cherry_usage);
1249 upstream = current_branch->merge[0]->dst;
1252 init_revisions(&revs, prefix);
1253 revs.diff = 1;
1254 revs.combine_merges = 0;
1255 revs.ignore_merges = 1;
1256 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1258 if (add_pending_commit(head, &revs, 0))
1259 die("Unknown commit %s", head);
1260 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1261 die("Unknown commit %s", upstream);
1263 /* Don't say anything if head and upstream are the same. */
1264 if (revs.pending.nr == 2) {
1265 struct object_array_entry *o = revs.pending.objects;
1266 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1267 return 0;
1270 get_patch_ids(&revs, &ids, prefix);
1272 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1273 die("Unknown commit %s", limit);
1275 /* reverse the list of commits */
1276 if (prepare_revision_walk(&revs))
1277 die("revision walk setup failed");
1278 while ((commit = get_revision(&revs)) != NULL) {
1279 /* ignore merges */
1280 if (commit->parents && commit->parents->next)
1281 continue;
1283 commit_list_insert(commit, &list);
1286 while (list) {
1287 char sign = '+';
1289 commit = list->item;
1290 if (has_commit_patch_id(commit, &ids))
1291 sign = '-';
1293 if (verbose) {
1294 struct strbuf buf = STRBUF_INIT;
1295 pretty_print_commit(CMIT_FMT_ONELINE, commit,
1296 &buf, 0, NULL, NULL, 0, 0);
1297 printf("%c %s %s\n", sign,
1298 sha1_to_hex(commit->object.sha1), buf.buf);
1299 strbuf_release(&buf);
1301 else {
1302 printf("%c %s\n", sign,
1303 sha1_to_hex(commit->object.sha1));
1306 list = list->next;
1309 free_patch_ids(&ids);
1310 return 0;