Merge branch 'jc/maint-1.6.0-blank-at-eof' (early part) into jc/maint-blank-at-eof
[git/raj.git] / builtin-log.c
blob8d93c1a2a476c58991d779cd5168c36189fff766
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 void cmd_log_init(int argc, const char **argv, const char *prefix,
31 struct rev_info *rev)
33 int i;
34 int decoration_style = 0;
36 rev->abbrev = DEFAULT_ABBREV;
37 rev->commit_format = CMIT_FMT_DEFAULT;
38 if (fmt_pretty)
39 get_commit_format(fmt_pretty, rev);
40 rev->verbose_header = 1;
41 DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
42 rev->show_root_diff = default_show_root;
43 rev->subject_prefix = fmt_patch_subject_prefix;
44 DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
46 if (default_date_mode)
47 rev->date_mode = parse_date_format(default_date_mode);
49 argc = setup_revisions(argc, argv, rev, "HEAD");
51 if (rev->diffopt.pickaxe || rev->diffopt.filter)
52 rev->always_show_header = 0;
53 if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
54 rev->always_show_header = 0;
55 if (rev->diffopt.nr_paths != 1)
56 usage("git logs can only follow renames on one pathname at a time");
58 for (i = 1; i < argc; i++) {
59 const char *arg = argv[i];
60 if (!strcmp(arg, "--decorate")) {
61 decoration_style = DECORATE_SHORT_REFS;
62 } else if (!prefixcmp(arg, "--decorate=")) {
63 const char *v = skip_prefix(arg, "--decorate=");
64 if (!strcmp(v, "full"))
65 decoration_style = DECORATE_FULL_REFS;
66 else if (!strcmp(v, "short"))
67 decoration_style = DECORATE_SHORT_REFS;
68 else
69 die("invalid --decorate option: %s", arg);
70 } else if (!strcmp(arg, "--source")) {
71 rev->show_source = 1;
72 } else
73 die("unrecognized argument: %s", arg);
75 if (decoration_style) {
76 rev->show_decorations = 1;
77 load_ref_decorations(decoration_style);
82 * This gives a rough estimate for how many commits we
83 * will print out in the list.
85 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
87 int n = 0;
89 while (list) {
90 struct commit *commit = list->item;
91 unsigned int flags = commit->object.flags;
92 list = list->next;
93 if (!(flags & (TREESAME | UNINTERESTING)))
94 n++;
96 return n;
99 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
101 if (rev->shown_one) {
102 rev->shown_one = 0;
103 if (rev->commit_format != CMIT_FMT_ONELINE)
104 putchar(rev->diffopt.line_termination);
106 printf("Final output: %d %s\n", nr, stage);
109 static struct itimerval early_output_timer;
111 static void log_show_early(struct rev_info *revs, struct commit_list *list)
113 int i = revs->early_output;
114 int show_header = 1;
116 sort_in_topological_order(&list, revs->lifo);
117 while (list && i) {
118 struct commit *commit = list->item;
119 switch (simplify_commit(revs, commit)) {
120 case commit_show:
121 if (show_header) {
122 int n = estimate_commit_count(revs, list);
123 show_early_header(revs, "incomplete", n);
124 show_header = 0;
126 log_tree_commit(revs, commit);
127 i--;
128 break;
129 case commit_ignore:
130 break;
131 case commit_error:
132 return;
134 list = list->next;
137 /* Did we already get enough commits for the early output? */
138 if (!i)
139 return;
142 * ..if no, then repeat it twice a second until we
143 * do.
145 * NOTE! We don't use "it_interval", because if the
146 * reader isn't listening, we want our output to be
147 * throttled by the writing, and not have the timer
148 * trigger every second even if we're blocked on a
149 * reader!
151 early_output_timer.it_value.tv_sec = 0;
152 early_output_timer.it_value.tv_usec = 500000;
153 setitimer(ITIMER_REAL, &early_output_timer, NULL);
156 static void early_output(int signal)
158 show_early_output = log_show_early;
161 static void setup_early_output(struct rev_info *rev)
163 struct sigaction sa;
166 * Set up the signal handler, minimally intrusively:
167 * we only set a single volatile integer word (not
168 * using sigatomic_t - trying to avoid unnecessary
169 * system dependencies and headers), and using
170 * SA_RESTART.
172 memset(&sa, 0, sizeof(sa));
173 sa.sa_handler = early_output;
174 sigemptyset(&sa.sa_mask);
175 sa.sa_flags = SA_RESTART;
176 sigaction(SIGALRM, &sa, NULL);
179 * If we can get the whole output in less than a
180 * tenth of a second, don't even bother doing the
181 * early-output thing..
183 * This is a one-time-only trigger.
185 early_output_timer.it_value.tv_sec = 0;
186 early_output_timer.it_value.tv_usec = 100000;
187 setitimer(ITIMER_REAL, &early_output_timer, NULL);
190 static void finish_early_output(struct rev_info *rev)
192 int n = estimate_commit_count(rev, rev->commits);
193 signal(SIGALRM, SIG_IGN);
194 show_early_header(rev, "done", n);
197 static int cmd_log_walk(struct rev_info *rev)
199 struct commit *commit;
201 if (rev->early_output)
202 setup_early_output(rev);
204 if (prepare_revision_walk(rev))
205 die("revision walk setup failed");
207 if (rev->early_output)
208 finish_early_output(rev);
211 * For --check and --exit-code, the exit code is based on CHECK_FAILED
212 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
213 * retain that state information if replacing rev->diffopt in this loop
215 while ((commit = get_revision(rev)) != NULL) {
216 log_tree_commit(rev, commit);
217 if (!rev->reflog_info) {
218 /* we allow cycles in reflog ancestry */
219 free(commit->buffer);
220 commit->buffer = NULL;
222 free_commit_list(commit->parents);
223 commit->parents = NULL;
225 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
226 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
227 return 02;
229 return diff_result_code(&rev->diffopt, 0);
232 static int git_log_config(const char *var, const char *value, void *cb)
234 if (!strcmp(var, "format.pretty"))
235 return git_config_string(&fmt_pretty, var, value);
236 if (!strcmp(var, "format.subjectprefix"))
237 return git_config_string(&fmt_patch_subject_prefix, var, value);
238 if (!strcmp(var, "log.date"))
239 return git_config_string(&default_date_mode, var, value);
240 if (!strcmp(var, "log.showroot")) {
241 default_show_root = git_config_bool(var, value);
242 return 0;
244 return git_diff_ui_config(var, value, cb);
247 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
249 struct rev_info rev;
251 git_config(git_log_config, NULL);
253 if (diff_use_color_default == -1)
254 diff_use_color_default = git_use_color_default;
256 init_revisions(&rev, prefix);
257 rev.diff = 1;
258 rev.simplify_history = 0;
259 cmd_log_init(argc, argv, prefix, &rev);
260 if (!rev.diffopt.output_format)
261 rev.diffopt.output_format = DIFF_FORMAT_RAW;
262 return cmd_log_walk(&rev);
265 static void show_tagger(char *buf, int len, struct rev_info *rev)
267 struct strbuf out = STRBUF_INIT;
269 pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
270 git_log_output_encoding ?
271 git_log_output_encoding: git_commit_encoding);
272 printf("%s", out.buf);
273 strbuf_release(&out);
276 static int show_object(const unsigned char *sha1, int show_tag_object,
277 struct rev_info *rev)
279 unsigned long size;
280 enum object_type type;
281 char *buf = read_sha1_file(sha1, &type, &size);
282 int offset = 0;
284 if (!buf)
285 return error("Could not read object %s", sha1_to_hex(sha1));
287 if (show_tag_object)
288 while (offset < size && buf[offset] != '\n') {
289 int new_offset = offset + 1;
290 while (new_offset < size && buf[new_offset++] != '\n')
291 ; /* do nothing */
292 if (!prefixcmp(buf + offset, "tagger "))
293 show_tagger(buf + offset + 7,
294 new_offset - offset - 7, rev);
295 offset = new_offset;
298 if (offset < size)
299 fwrite(buf + offset, size - offset, 1, stdout);
300 free(buf);
301 return 0;
304 static int show_tree_object(const unsigned char *sha1,
305 const char *base, int baselen,
306 const char *pathname, unsigned mode, int stage, void *context)
308 printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
309 return 0;
312 int cmd_show(int argc, const char **argv, const char *prefix)
314 struct rev_info rev;
315 struct object_array_entry *objects;
316 int i, count, ret = 0;
318 git_config(git_log_config, NULL);
320 if (diff_use_color_default == -1)
321 diff_use_color_default = git_use_color_default;
323 init_revisions(&rev, prefix);
324 rev.diff = 1;
325 rev.combine_merges = 1;
326 rev.dense_combined_merges = 1;
327 rev.always_show_header = 1;
328 rev.ignore_merges = 0;
329 rev.no_walk = 1;
330 cmd_log_init(argc, argv, prefix, &rev);
332 count = rev.pending.nr;
333 objects = rev.pending.objects;
334 for (i = 0; i < count && !ret; i++) {
335 struct object *o = objects[i].item;
336 const char *name = objects[i].name;
337 switch (o->type) {
338 case OBJ_BLOB:
339 ret = show_object(o->sha1, 0, NULL);
340 break;
341 case OBJ_TAG: {
342 struct tag *t = (struct tag *)o;
344 if (rev.shown_one)
345 putchar('\n');
346 printf("%stag %s%s\n",
347 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
348 t->tag,
349 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
350 ret = show_object(o->sha1, 1, &rev);
351 rev.shown_one = 1;
352 if (ret)
353 break;
354 o = parse_object(t->tagged->sha1);
355 if (!o)
356 ret = error("Could not read object %s",
357 sha1_to_hex(t->tagged->sha1));
358 objects[i].item = o;
359 i--;
360 break;
362 case OBJ_TREE:
363 if (rev.shown_one)
364 putchar('\n');
365 printf("%stree %s%s\n\n",
366 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
367 name,
368 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
369 read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
370 show_tree_object, NULL);
371 rev.shown_one = 1;
372 break;
373 case OBJ_COMMIT:
374 rev.pending.nr = rev.pending.alloc = 0;
375 rev.pending.objects = NULL;
376 add_object_array(o, name, &rev.pending);
377 ret = cmd_log_walk(&rev);
378 break;
379 default:
380 ret = error("Unknown type: %d", o->type);
383 free(objects);
384 return ret;
388 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
390 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
392 struct rev_info rev;
394 git_config(git_log_config, NULL);
396 if (diff_use_color_default == -1)
397 diff_use_color_default = git_use_color_default;
399 init_revisions(&rev, prefix);
400 init_reflog_walk(&rev.reflog_info);
401 rev.abbrev_commit = 1;
402 rev.verbose_header = 1;
403 cmd_log_init(argc, argv, prefix, &rev);
406 * This means that we override whatever commit format the user gave
407 * on the cmd line. Sad, but cmd_log_init() currently doesn't
408 * allow us to set a different default.
410 rev.commit_format = CMIT_FMT_ONELINE;
411 rev.use_terminator = 1;
412 rev.always_show_header = 1;
415 * We get called through "git reflog", so unlike the other log
416 * routines, we need to set up our pager manually..
418 setup_pager();
420 return cmd_log_walk(&rev);
423 int cmd_log(int argc, const char **argv, const char *prefix)
425 struct rev_info rev;
427 git_config(git_log_config, NULL);
429 if (diff_use_color_default == -1)
430 diff_use_color_default = git_use_color_default;
432 init_revisions(&rev, prefix);
433 rev.always_show_header = 1;
434 cmd_log_init(argc, argv, prefix, &rev);
435 return cmd_log_walk(&rev);
438 /* format-patch */
440 static const char *fmt_patch_suffix = ".patch";
441 static int numbered = 0;
442 static int auto_number = 1;
444 static char *default_attach = NULL;
446 static char **extra_hdr;
447 static int extra_hdr_nr;
448 static int extra_hdr_alloc;
450 static char **extra_to;
451 static int extra_to_nr;
452 static int extra_to_alloc;
454 static char **extra_cc;
455 static int extra_cc_nr;
456 static int extra_cc_alloc;
458 static void add_header(const char *value)
460 int len = strlen(value);
461 while (len && value[len - 1] == '\n')
462 len--;
463 if (!strncasecmp(value, "to: ", 4)) {
464 ALLOC_GROW(extra_to, extra_to_nr + 1, extra_to_alloc);
465 extra_to[extra_to_nr++] = xstrndup(value + 4, len - 4);
466 return;
468 if (!strncasecmp(value, "cc: ", 4)) {
469 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
470 extra_cc[extra_cc_nr++] = xstrndup(value + 4, len - 4);
471 return;
473 ALLOC_GROW(extra_hdr, extra_hdr_nr + 1, extra_hdr_alloc);
474 extra_hdr[extra_hdr_nr++] = xstrndup(value, len);
477 #define THREAD_SHALLOW 1
478 #define THREAD_DEEP 2
479 static int thread = 0;
480 static int do_signoff = 0;
482 static int git_format_config(const char *var, const char *value, void *cb)
484 if (!strcmp(var, "format.headers")) {
485 if (!value)
486 die("format.headers without value");
487 add_header(value);
488 return 0;
490 if (!strcmp(var, "format.suffix"))
491 return git_config_string(&fmt_patch_suffix, var, value);
492 if (!strcmp(var, "format.cc")) {
493 if (!value)
494 return config_error_nonbool(var);
495 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
496 extra_cc[extra_cc_nr++] = xstrdup(value);
497 return 0;
499 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
500 return 0;
502 if (!strcmp(var, "format.numbered")) {
503 if (value && !strcasecmp(value, "auto")) {
504 auto_number = 1;
505 return 0;
507 numbered = git_config_bool(var, value);
508 auto_number = auto_number && numbered;
509 return 0;
511 if (!strcmp(var, "format.attach")) {
512 if (value && *value)
513 default_attach = xstrdup(value);
514 else
515 default_attach = xstrdup(git_version_string);
516 return 0;
518 if (!strcmp(var, "format.thread")) {
519 if (value && !strcasecmp(value, "deep")) {
520 thread = THREAD_DEEP;
521 return 0;
523 if (value && !strcasecmp(value, "shallow")) {
524 thread = THREAD_SHALLOW;
525 return 0;
527 thread = git_config_bool(var, value) && THREAD_SHALLOW;
528 return 0;
530 if (!strcmp(var, "format.signoff")) {
531 do_signoff = git_config_bool(var, value);
532 return 0;
535 return git_log_config(var, value, cb);
538 static FILE *realstdout = NULL;
539 static const char *output_directory = NULL;
540 static int outdir_offset;
542 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
544 struct strbuf filename = STRBUF_INIT;
545 int suffix_len = strlen(fmt_patch_suffix) + 1;
547 if (output_directory) {
548 strbuf_addstr(&filename, output_directory);
549 if (filename.len >=
550 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
551 return error("name of output directory is too long");
552 if (filename.buf[filename.len - 1] != '/')
553 strbuf_addch(&filename, '/');
556 get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
558 if (!DIFF_OPT_TST(&rev->diffopt, QUIET))
559 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
561 if (freopen(filename.buf, "w", stdout) == NULL)
562 return error("Cannot open patch file %s", filename.buf);
564 strbuf_release(&filename);
565 return 0;
568 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
570 struct rev_info check_rev;
571 struct commit *commit;
572 struct object *o1, *o2;
573 unsigned flags1, flags2;
575 if (rev->pending.nr != 2)
576 die("Need exactly one range.");
578 o1 = rev->pending.objects[0].item;
579 flags1 = o1->flags;
580 o2 = rev->pending.objects[1].item;
581 flags2 = o2->flags;
583 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
584 die("Not a range.");
586 init_patch_ids(ids);
588 /* given a range a..b get all patch ids for b..a */
589 init_revisions(&check_rev, prefix);
590 o1->flags ^= UNINTERESTING;
591 o2->flags ^= UNINTERESTING;
592 add_pending_object(&check_rev, o1, "o1");
593 add_pending_object(&check_rev, o2, "o2");
594 if (prepare_revision_walk(&check_rev))
595 die("revision walk setup failed");
597 while ((commit = get_revision(&check_rev)) != NULL) {
598 /* ignore merges */
599 if (commit->parents && commit->parents->next)
600 continue;
602 add_commit_patch_id(commit, ids);
605 /* reset for next revision walk */
606 clear_commit_marks((struct commit *)o1,
607 SEEN | UNINTERESTING | SHOWN | ADDED);
608 clear_commit_marks((struct commit *)o2,
609 SEEN | UNINTERESTING | SHOWN | ADDED);
610 o1->flags = flags1;
611 o2->flags = flags2;
614 static void gen_message_id(struct rev_info *info, char *base)
616 const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
617 const char *email_start = strrchr(committer, '<');
618 const char *email_end = strrchr(committer, '>');
619 struct strbuf buf = STRBUF_INIT;
620 if (!email_start || !email_end || email_start > email_end - 1)
621 die("Could not extract email from committer identity.");
622 strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
623 (unsigned long) time(NULL),
624 (int)(email_end - email_start - 1), email_start + 1);
625 info->message_id = strbuf_detach(&buf, NULL);
628 static void make_cover_letter(struct rev_info *rev, int use_stdout,
629 int numbered, int numbered_files,
630 struct commit *origin,
631 int nr, struct commit **list, struct commit *head)
633 const char *committer;
634 const char *subject_start = NULL;
635 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
636 const char *msg;
637 const char *extra_headers = rev->extra_headers;
638 struct shortlog log;
639 struct strbuf sb = STRBUF_INIT;
640 int i;
641 const char *encoding = "UTF-8";
642 struct diff_options opts;
643 int need_8bit_cte = 0;
644 struct commit *commit = NULL;
646 if (rev->commit_format != CMIT_FMT_EMAIL)
647 die("Cover letter needs email format");
649 committer = git_committer_info(0);
651 if (!numbered_files) {
653 * We fake a commit for the cover letter so we get the filename
654 * desired.
656 commit = xcalloc(1, sizeof(*commit));
657 commit->buffer = xmalloc(400);
658 snprintf(commit->buffer, 400,
659 "tree 0000000000000000000000000000000000000000\n"
660 "parent %s\n"
661 "author %s\n"
662 "committer %s\n\n"
663 "cover letter\n",
664 sha1_to_hex(head->object.sha1), committer, committer);
667 if (!use_stdout && reopen_stdout(commit, rev))
668 return;
670 if (commit) {
672 free(commit->buffer);
673 free(commit);
676 log_write_email_headers(rev, head, &subject_start, &extra_headers,
677 &need_8bit_cte);
679 for (i = 0; !need_8bit_cte && i < nr; i++)
680 if (has_non_ascii(list[i]->buffer))
681 need_8bit_cte = 1;
683 msg = body;
684 pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
685 encoding);
686 pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
687 encoding, need_8bit_cte);
688 pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
689 printf("%s\n", sb.buf);
691 strbuf_release(&sb);
693 shortlog_init(&log);
694 log.wrap_lines = 1;
695 log.wrap = 72;
696 log.in1 = 2;
697 log.in2 = 4;
698 for (i = 0; i < nr; i++)
699 shortlog_add_commit(&log, list[i]);
701 shortlog_output(&log);
704 * We can only do diffstat with a unique reference point
706 if (!origin)
707 return;
709 memcpy(&opts, &rev->diffopt, sizeof(opts));
710 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
712 diff_setup_done(&opts);
714 diff_tree_sha1(origin->tree->object.sha1,
715 head->tree->object.sha1,
716 "", &opts);
717 diffcore_std(&opts);
718 diff_flush(&opts);
720 printf("\n");
723 static const char *clean_message_id(const char *msg_id)
725 char ch;
726 const char *a, *z, *m;
728 m = msg_id;
729 while ((ch = *m) && (isspace(ch) || (ch == '<')))
730 m++;
731 a = m;
732 z = NULL;
733 while ((ch = *m)) {
734 if (!isspace(ch) && (ch != '>'))
735 z = m;
736 m++;
738 if (!z)
739 die("insane in-reply-to: %s", msg_id);
740 if (++z == m)
741 return a;
742 return xmemdupz(a, z - a);
745 static const char *set_outdir(const char *prefix, const char *output_directory)
747 if (output_directory && is_absolute_path(output_directory))
748 return output_directory;
750 if (!prefix || !*prefix) {
751 if (output_directory)
752 return output_directory;
753 /* The user did not explicitly ask for "./" */
754 outdir_offset = 2;
755 return "./";
758 outdir_offset = strlen(prefix);
759 if (!output_directory)
760 return prefix;
762 return xstrdup(prefix_filename(prefix, outdir_offset,
763 output_directory));
766 static const char * const builtin_format_patch_usage[] = {
767 "git format-patch [options] [<since> | <revision range>]",
768 NULL
771 static int keep_subject = 0;
773 static int keep_callback(const struct option *opt, const char *arg, int unset)
775 ((struct rev_info *)opt->value)->total = -1;
776 keep_subject = 1;
777 return 0;
780 static int subject_prefix = 0;
782 static int subject_prefix_callback(const struct option *opt, const char *arg,
783 int unset)
785 subject_prefix = 1;
786 ((struct rev_info *)opt->value)->subject_prefix = arg;
787 return 0;
790 static int numbered_cmdline_opt = 0;
792 static int numbered_callback(const struct option *opt, const char *arg,
793 int unset)
795 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
796 if (unset)
797 auto_number = 0;
798 return 0;
801 static int no_numbered_callback(const struct option *opt, const char *arg,
802 int unset)
804 return numbered_callback(opt, arg, 1);
807 static int output_directory_callback(const struct option *opt, const char *arg,
808 int unset)
810 const char **dir = (const char **)opt->value;
811 if (*dir)
812 die("Two output directories?");
813 *dir = arg;
814 return 0;
817 static int thread_callback(const struct option *opt, const char *arg, int unset)
819 int *thread = (int *)opt->value;
820 if (unset)
821 *thread = 0;
822 else if (!arg || !strcmp(arg, "shallow"))
823 *thread = THREAD_SHALLOW;
824 else if (!strcmp(arg, "deep"))
825 *thread = THREAD_DEEP;
826 else
827 return 1;
828 return 0;
831 static int attach_callback(const struct option *opt, const char *arg, int unset)
833 struct rev_info *rev = (struct rev_info *)opt->value;
834 if (unset)
835 rev->mime_boundary = NULL;
836 else if (arg)
837 rev->mime_boundary = arg;
838 else
839 rev->mime_boundary = git_version_string;
840 rev->no_inline = unset ? 0 : 1;
841 return 0;
844 static int inline_callback(const struct option *opt, const char *arg, int unset)
846 struct rev_info *rev = (struct rev_info *)opt->value;
847 if (unset)
848 rev->mime_boundary = NULL;
849 else if (arg)
850 rev->mime_boundary = arg;
851 else
852 rev->mime_boundary = git_version_string;
853 rev->no_inline = 0;
854 return 0;
857 static int header_callback(const struct option *opt, const char *arg, int unset)
859 add_header(arg);
860 return 0;
863 static int cc_callback(const struct option *opt, const char *arg, int unset)
865 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
866 extra_cc[extra_cc_nr++] = xstrdup(arg);
867 return 0;
870 int cmd_format_patch(int argc, const char **argv, const char *prefix)
872 struct commit *commit;
873 struct commit **list = NULL;
874 struct rev_info rev;
875 int nr = 0, total, i;
876 int use_stdout = 0;
877 int start_number = -1;
878 int numbered_files = 0; /* _just_ numbers */
879 int ignore_if_in_upstream = 0;
880 int cover_letter = 0;
881 int boundary_count = 0;
882 int no_binary_diff = 0;
883 struct commit *origin = NULL, *head = NULL;
884 const char *in_reply_to = NULL;
885 struct patch_ids ids;
886 char *add_signoff = NULL;
887 struct strbuf buf = STRBUF_INIT;
888 const struct option builtin_format_patch_options[] = {
889 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
890 "use [PATCH n/m] even with a single patch",
891 PARSE_OPT_NOARG, numbered_callback },
892 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
893 "use [PATCH] even with multiple patches",
894 PARSE_OPT_NOARG, no_numbered_callback },
895 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
896 OPT_BOOLEAN(0, "stdout", &use_stdout,
897 "print patches to standard out"),
898 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
899 "generate a cover letter"),
900 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
901 "use simple number sequence for output file names"),
902 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
903 "use <sfx> instead of '.patch'"),
904 OPT_INTEGER(0, "start-number", &start_number,
905 "start numbering patches at <n> instead of 1"),
906 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
907 "Use [<prefix>] instead of [PATCH]",
908 PARSE_OPT_NONEG, subject_prefix_callback },
909 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
910 "dir", "store resulting files in <dir>",
911 PARSE_OPT_NONEG, output_directory_callback },
912 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
913 "don't strip/add [PATCH]",
914 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
915 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
916 "don't output binary diffs"),
917 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
918 "don't include a patch matching a commit upstream"),
919 OPT_GROUP("Messaging"),
920 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
921 "add email header", PARSE_OPT_NONEG,
922 header_callback },
923 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
924 PARSE_OPT_NONEG, cc_callback },
925 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
926 "make first mail a reply to <message-id>"),
927 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
928 "attach the patch", PARSE_OPT_OPTARG,
929 attach_callback },
930 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
931 "inline the patch",
932 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
933 inline_callback },
934 { OPTION_CALLBACK, 0, "thread", &thread, "style",
935 "enable message threading, styles: shallow, deep",
936 PARSE_OPT_OPTARG, thread_callback },
937 OPT_END()
940 git_config(git_format_config, NULL);
941 init_revisions(&rev, prefix);
942 rev.commit_format = CMIT_FMT_EMAIL;
943 rev.verbose_header = 1;
944 rev.diff = 1;
945 rev.combine_merges = 0;
946 rev.ignore_merges = 1;
947 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
949 rev.subject_prefix = fmt_patch_subject_prefix;
951 if (default_attach) {
952 rev.mime_boundary = default_attach;
953 rev.no_inline = 1;
957 * Parse the arguments before setup_revisions(), or something
958 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
959 * possibly a valid SHA1.
961 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
962 builtin_format_patch_usage,
963 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN);
965 if (do_signoff) {
966 const char *committer;
967 const char *endpos;
968 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
969 endpos = strchr(committer, '>');
970 if (!endpos)
971 die("bogus committer info %s", committer);
972 add_signoff = xmemdupz(committer, endpos - committer + 1);
975 for (i = 0; i < extra_hdr_nr; i++) {
976 strbuf_addstr(&buf, extra_hdr[i]);
977 strbuf_addch(&buf, '\n');
980 if (extra_to_nr)
981 strbuf_addstr(&buf, "To: ");
982 for (i = 0; i < extra_to_nr; i++) {
983 if (i)
984 strbuf_addstr(&buf, " ");
985 strbuf_addstr(&buf, extra_to[i]);
986 if (i + 1 < extra_to_nr)
987 strbuf_addch(&buf, ',');
988 strbuf_addch(&buf, '\n');
991 if (extra_cc_nr)
992 strbuf_addstr(&buf, "Cc: ");
993 for (i = 0; i < extra_cc_nr; i++) {
994 if (i)
995 strbuf_addstr(&buf, " ");
996 strbuf_addstr(&buf, extra_cc[i]);
997 if (i + 1 < extra_cc_nr)
998 strbuf_addch(&buf, ',');
999 strbuf_addch(&buf, '\n');
1002 rev.extra_headers = strbuf_detach(&buf, NULL);
1004 if (start_number < 0)
1005 start_number = 1;
1008 * If numbered is set solely due to format.numbered in config,
1009 * and it would conflict with --keep-subject (-k) from the
1010 * command line, reset "numbered".
1012 if (numbered && keep_subject && !numbered_cmdline_opt)
1013 numbered = 0;
1015 if (numbered && keep_subject)
1016 die ("-n and -k are mutually exclusive.");
1017 if (keep_subject && subject_prefix)
1018 die ("--subject-prefix and -k are mutually exclusive.");
1020 argc = setup_revisions(argc, argv, &rev, "HEAD");
1021 if (argc > 1)
1022 die ("unrecognized argument: %s", argv[1]);
1024 if (!rev.diffopt.output_format
1025 || rev.diffopt.output_format == DIFF_FORMAT_PATCH)
1026 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
1028 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1029 DIFF_OPT_SET(&rev.diffopt, BINARY);
1031 if (!use_stdout)
1032 output_directory = set_outdir(prefix, output_directory);
1034 if (output_directory) {
1035 if (use_stdout)
1036 die("standard output, or directory, which one?");
1037 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1038 die_errno("Could not create directory '%s'",
1039 output_directory);
1042 if (rev.pending.nr == 1) {
1043 if (rev.max_count < 0 && !rev.show_root_diff) {
1045 * This is traditional behaviour of "git format-patch
1046 * origin" that prepares what the origin side still
1047 * does not have.
1049 rev.pending.objects[0].item->flags |= UNINTERESTING;
1050 add_head_to_pending(&rev);
1053 * Otherwise, it is "format-patch -22 HEAD", and/or
1054 * "format-patch --root HEAD". The user wants
1055 * get_revision() to do the usual traversal.
1060 * We cannot move this anywhere earlier because we do want to
1061 * know if --root was given explicitly from the comand line.
1063 rev.show_root_diff = 1;
1065 if (cover_letter) {
1066 /* remember the range */
1067 int i;
1068 for (i = 0; i < rev.pending.nr; i++) {
1069 struct object *o = rev.pending.objects[i].item;
1070 if (!(o->flags & UNINTERESTING))
1071 head = (struct commit *)o;
1073 /* We can't generate a cover letter without any patches */
1074 if (!head)
1075 return 0;
1078 if (ignore_if_in_upstream)
1079 get_patch_ids(&rev, &ids, prefix);
1081 if (!use_stdout)
1082 realstdout = xfdopen(xdup(1), "w");
1084 if (prepare_revision_walk(&rev))
1085 die("revision walk setup failed");
1086 rev.boundary = 1;
1087 while ((commit = get_revision(&rev)) != NULL) {
1088 if (commit->object.flags & BOUNDARY) {
1089 boundary_count++;
1090 origin = (boundary_count == 1) ? commit : NULL;
1091 continue;
1094 /* ignore merges */
1095 if (commit->parents && commit->parents->next)
1096 continue;
1098 if (ignore_if_in_upstream &&
1099 has_commit_patch_id(commit, &ids))
1100 continue;
1102 nr++;
1103 list = xrealloc(list, nr * sizeof(list[0]));
1104 list[nr - 1] = commit;
1106 total = nr;
1107 if (!keep_subject && auto_number && total > 1)
1108 numbered = 1;
1109 if (numbered)
1110 rev.total = total + start_number - 1;
1111 if (in_reply_to || thread || cover_letter)
1112 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1113 if (in_reply_to) {
1114 const char *msgid = clean_message_id(in_reply_to);
1115 string_list_append(msgid, rev.ref_message_ids);
1117 rev.numbered_files = numbered_files;
1118 rev.patch_suffix = fmt_patch_suffix;
1119 if (cover_letter) {
1120 if (thread)
1121 gen_message_id(&rev, "cover");
1122 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1123 origin, nr, list, head);
1124 total++;
1125 start_number--;
1127 rev.add_signoff = add_signoff;
1128 while (0 <= --nr) {
1129 int shown;
1130 commit = list[nr];
1131 rev.nr = total - nr + (start_number - 1);
1132 /* Make the second and subsequent mails replies to the first */
1133 if (thread) {
1134 /* Have we already had a message ID? */
1135 if (rev.message_id) {
1137 * For deep threading: make every mail
1138 * a reply to the previous one, no
1139 * matter what other options are set.
1141 * For shallow threading:
1143 * Without --cover-letter and
1144 * --in-reply-to, make every mail a
1145 * reply to the one before.
1147 * With --in-reply-to but no
1148 * --cover-letter, make every mail a
1149 * reply to the <reply-to>.
1151 * With --cover-letter, make every
1152 * mail but the cover letter a reply
1153 * to the cover letter. The cover
1154 * letter is a reply to the
1155 * --in-reply-to, if specified.
1157 if (thread == THREAD_SHALLOW
1158 && rev.ref_message_ids->nr > 0
1159 && (!cover_letter || rev.nr > 1))
1160 free(rev.message_id);
1161 else
1162 string_list_append(rev.message_id,
1163 rev.ref_message_ids);
1165 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1168 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1169 &rev))
1170 die("Failed to create output files");
1171 shown = log_tree_commit(&rev, commit);
1172 free(commit->buffer);
1173 commit->buffer = NULL;
1175 /* We put one extra blank line between formatted
1176 * patches and this flag is used by log-tree code
1177 * to see if it needs to emit a LF before showing
1178 * the log; when using one file per patch, we do
1179 * not want the extra blank line.
1181 if (!use_stdout)
1182 rev.shown_one = 0;
1183 if (shown) {
1184 if (rev.mime_boundary)
1185 printf("\n--%s%s--\n\n\n",
1186 mime_boundary_leader,
1187 rev.mime_boundary);
1188 else
1189 printf("-- \n%s\n\n", git_version_string);
1191 if (!use_stdout)
1192 fclose(stdout);
1194 free(list);
1195 if (ignore_if_in_upstream)
1196 free_patch_ids(&ids);
1197 return 0;
1200 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1202 unsigned char sha1[20];
1203 if (get_sha1(arg, sha1) == 0) {
1204 struct commit *commit = lookup_commit_reference(sha1);
1205 if (commit) {
1206 commit->object.flags |= flags;
1207 add_pending_object(revs, &commit->object, arg);
1208 return 0;
1211 return -1;
1214 static const char cherry_usage[] =
1215 "git cherry [-v] [<upstream> [<head> [<limit>]]]";
1216 int cmd_cherry(int argc, const char **argv, const char *prefix)
1218 struct rev_info revs;
1219 struct patch_ids ids;
1220 struct commit *commit;
1221 struct commit_list *list = NULL;
1222 struct branch *current_branch;
1223 const char *upstream;
1224 const char *head = "HEAD";
1225 const char *limit = NULL;
1226 int verbose = 0;
1228 if (argc > 1 && !strcmp(argv[1], "-v")) {
1229 verbose = 1;
1230 argc--;
1231 argv++;
1234 switch (argc) {
1235 case 4:
1236 limit = argv[3];
1237 /* FALLTHROUGH */
1238 case 3:
1239 head = argv[2];
1240 /* FALLTHROUGH */
1241 case 2:
1242 upstream = argv[1];
1243 break;
1244 default:
1245 current_branch = branch_get(NULL);
1246 if (!current_branch || !current_branch->merge
1247 || !current_branch->merge[0]
1248 || !current_branch->merge[0]->dst) {
1249 fprintf(stderr, "Could not find a tracked"
1250 " remote branch, please"
1251 " specify <upstream> manually.\n");
1252 usage(cherry_usage);
1255 upstream = current_branch->merge[0]->dst;
1258 init_revisions(&revs, prefix);
1259 revs.diff = 1;
1260 revs.combine_merges = 0;
1261 revs.ignore_merges = 1;
1262 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1264 if (add_pending_commit(head, &revs, 0))
1265 die("Unknown commit %s", head);
1266 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1267 die("Unknown commit %s", upstream);
1269 /* Don't say anything if head and upstream are the same. */
1270 if (revs.pending.nr == 2) {
1271 struct object_array_entry *o = revs.pending.objects;
1272 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1273 return 0;
1276 get_patch_ids(&revs, &ids, prefix);
1278 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1279 die("Unknown commit %s", limit);
1281 /* reverse the list of commits */
1282 if (prepare_revision_walk(&revs))
1283 die("revision walk setup failed");
1284 while ((commit = get_revision(&revs)) != NULL) {
1285 /* ignore merges */
1286 if (commit->parents && commit->parents->next)
1287 continue;
1289 commit_list_insert(commit, &list);
1292 while (list) {
1293 char sign = '+';
1295 commit = list->item;
1296 if (has_commit_patch_id(commit, &ids))
1297 sign = '-';
1299 if (verbose) {
1300 struct strbuf buf = STRBUF_INIT;
1301 pretty_print_commit(CMIT_FMT_ONELINE, commit,
1302 &buf, 0, NULL, NULL, 0, 0);
1303 printf("%c %s %s\n", sign,
1304 sha1_to_hex(commit->object.sha1), buf.buf);
1305 strbuf_release(&buf);
1307 else {
1308 printf("%c %s\n", sign,
1309 sha1_to_hex(commit->object.sha1));
1312 list = list->next;
1315 free_patch_ids(&ids);
1316 return 0;