grep: NUL terminate input from a file
[git/raj.git] / builtin-log.c
blob0cf978e0942a896606db9e4c17c9b9f0f3417daa
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;
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);
53 argc = setup_revisions(argc, argv, rev, "HEAD");
55 if (rev->diffopt.pickaxe || rev->diffopt.filter)
56 rev->always_show_header = 0;
57 if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
58 rev->always_show_header = 0;
59 if (rev->diffopt.nr_paths != 1)
60 usage("git logs can only follow renames on one pathname at a time");
62 for (i = 1; i < argc; i++) {
63 const char *arg = argv[i];
64 if (!strcmp(arg, "--decorate")) {
65 decoration_style = DECORATE_SHORT_REFS;
66 } else if (!prefixcmp(arg, "--decorate=")) {
67 const char *v = skip_prefix(arg, "--decorate=");
68 if (!strcmp(v, "full"))
69 decoration_style = DECORATE_FULL_REFS;
70 else if (!strcmp(v, "short"))
71 decoration_style = DECORATE_SHORT_REFS;
72 else
73 die("invalid --decorate option: %s", arg);
74 } else if (!strcmp(arg, "--source")) {
75 rev->show_source = 1;
76 } else if (!strcmp(arg, "-h")) {
77 usage(builtin_log_usage);
78 } else
79 die("unrecognized argument: %s", arg);
81 if (decoration_style) {
82 rev->show_decorations = 1;
83 load_ref_decorations(decoration_style);
88 * This gives a rough estimate for how many commits we
89 * will print out in the list.
91 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
93 int n = 0;
95 while (list) {
96 struct commit *commit = list->item;
97 unsigned int flags = commit->object.flags;
98 list = list->next;
99 if (!(flags & (TREESAME | UNINTERESTING)))
100 n++;
102 return n;
105 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
107 if (rev->shown_one) {
108 rev->shown_one = 0;
109 if (rev->commit_format != CMIT_FMT_ONELINE)
110 putchar(rev->diffopt.line_termination);
112 printf("Final output: %d %s\n", nr, stage);
115 static struct itimerval early_output_timer;
117 static void log_show_early(struct rev_info *revs, struct commit_list *list)
119 int i = revs->early_output;
120 int show_header = 1;
122 sort_in_topological_order(&list, revs->lifo);
123 while (list && i) {
124 struct commit *commit = list->item;
125 switch (simplify_commit(revs, commit)) {
126 case commit_show:
127 if (show_header) {
128 int n = estimate_commit_count(revs, list);
129 show_early_header(revs, "incomplete", n);
130 show_header = 0;
132 log_tree_commit(revs, commit);
133 i--;
134 break;
135 case commit_ignore:
136 break;
137 case commit_error:
138 return;
140 list = list->next;
143 /* Did we already get enough commits for the early output? */
144 if (!i)
145 return;
148 * ..if no, then repeat it twice a second until we
149 * do.
151 * NOTE! We don't use "it_interval", because if the
152 * reader isn't listening, we want our output to be
153 * throttled by the writing, and not have the timer
154 * trigger every second even if we're blocked on a
155 * reader!
157 early_output_timer.it_value.tv_sec = 0;
158 early_output_timer.it_value.tv_usec = 500000;
159 setitimer(ITIMER_REAL, &early_output_timer, NULL);
162 static void early_output(int signal)
164 show_early_output = log_show_early;
167 static void setup_early_output(struct rev_info *rev)
169 struct sigaction sa;
172 * Set up the signal handler, minimally intrusively:
173 * we only set a single volatile integer word (not
174 * using sigatomic_t - trying to avoid unnecessary
175 * system dependencies and headers), and using
176 * SA_RESTART.
178 memset(&sa, 0, sizeof(sa));
179 sa.sa_handler = early_output;
180 sigemptyset(&sa.sa_mask);
181 sa.sa_flags = SA_RESTART;
182 sigaction(SIGALRM, &sa, NULL);
185 * If we can get the whole output in less than a
186 * tenth of a second, don't even bother doing the
187 * early-output thing..
189 * This is a one-time-only trigger.
191 early_output_timer.it_value.tv_sec = 0;
192 early_output_timer.it_value.tv_usec = 100000;
193 setitimer(ITIMER_REAL, &early_output_timer, NULL);
196 static void finish_early_output(struct rev_info *rev)
198 int n = estimate_commit_count(rev, rev->commits);
199 signal(SIGALRM, SIG_IGN);
200 show_early_header(rev, "done", n);
203 static int cmd_log_walk(struct rev_info *rev)
205 struct commit *commit;
207 if (rev->early_output)
208 setup_early_output(rev);
210 if (prepare_revision_walk(rev))
211 die("revision walk setup failed");
213 if (rev->early_output)
214 finish_early_output(rev);
217 * For --check and --exit-code, the exit code is based on CHECK_FAILED
218 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
219 * retain that state information if replacing rev->diffopt in this loop
221 while ((commit = get_revision(rev)) != NULL) {
222 log_tree_commit(rev, commit);
223 if (!rev->reflog_info) {
224 /* we allow cycles in reflog ancestry */
225 free(commit->buffer);
226 commit->buffer = NULL;
228 free_commit_list(commit->parents);
229 commit->parents = NULL;
231 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
232 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
233 return 02;
235 return diff_result_code(&rev->diffopt, 0);
238 static int git_log_config(const char *var, const char *value, void *cb)
240 if (!strcmp(var, "format.pretty"))
241 return git_config_string(&fmt_pretty, var, value);
242 if (!strcmp(var, "format.subjectprefix"))
243 return git_config_string(&fmt_patch_subject_prefix, var, value);
244 if (!strcmp(var, "log.date"))
245 return git_config_string(&default_date_mode, var, value);
246 if (!strcmp(var, "log.showroot")) {
247 default_show_root = git_config_bool(var, value);
248 return 0;
250 return git_diff_ui_config(var, value, cb);
253 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
255 struct rev_info rev;
257 git_config(git_log_config, NULL);
259 if (diff_use_color_default == -1)
260 diff_use_color_default = git_use_color_default;
262 init_revisions(&rev, prefix);
263 rev.diff = 1;
264 rev.simplify_history = 0;
265 cmd_log_init(argc, argv, prefix, &rev);
266 if (!rev.diffopt.output_format)
267 rev.diffopt.output_format = DIFF_FORMAT_RAW;
268 return cmd_log_walk(&rev);
271 static void show_tagger(char *buf, int len, struct rev_info *rev)
273 struct strbuf out = STRBUF_INIT;
275 pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
276 git_log_output_encoding ?
277 git_log_output_encoding: git_commit_encoding);
278 printf("%s", out.buf);
279 strbuf_release(&out);
282 static int show_object(const unsigned char *sha1, int show_tag_object,
283 struct rev_info *rev)
285 unsigned long size;
286 enum object_type type;
287 char *buf = read_sha1_file(sha1, &type, &size);
288 int offset = 0;
290 if (!buf)
291 return error("Could not read object %s", sha1_to_hex(sha1));
293 if (show_tag_object)
294 while (offset < size && buf[offset] != '\n') {
295 int new_offset = offset + 1;
296 while (new_offset < size && buf[new_offset++] != '\n')
297 ; /* do nothing */
298 if (!prefixcmp(buf + offset, "tagger "))
299 show_tagger(buf + offset + 7,
300 new_offset - offset - 7, rev);
301 offset = new_offset;
304 if (offset < size)
305 fwrite(buf + offset, size - offset, 1, stdout);
306 free(buf);
307 return 0;
310 static int show_tree_object(const unsigned char *sha1,
311 const char *base, int baselen,
312 const char *pathname, unsigned mode, int stage, void *context)
314 printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
315 return 0;
318 int cmd_show(int argc, const char **argv, const char *prefix)
320 struct rev_info rev;
321 struct object_array_entry *objects;
322 int i, count, ret = 0;
324 git_config(git_log_config, NULL);
326 if (diff_use_color_default == -1)
327 diff_use_color_default = git_use_color_default;
329 init_revisions(&rev, prefix);
330 rev.diff = 1;
331 rev.combine_merges = 1;
332 rev.dense_combined_merges = 1;
333 rev.always_show_header = 1;
334 rev.ignore_merges = 0;
335 rev.no_walk = 1;
336 cmd_log_init(argc, argv, prefix, &rev);
338 count = rev.pending.nr;
339 objects = rev.pending.objects;
340 for (i = 0; i < count && !ret; i++) {
341 struct object *o = objects[i].item;
342 const char *name = objects[i].name;
343 switch (o->type) {
344 case OBJ_BLOB:
345 ret = show_object(o->sha1, 0, NULL);
346 break;
347 case OBJ_TAG: {
348 struct tag *t = (struct tag *)o;
350 if (rev.shown_one)
351 putchar('\n');
352 printf("%stag %s%s\n",
353 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
354 t->tag,
355 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
356 ret = show_object(o->sha1, 1, &rev);
357 rev.shown_one = 1;
358 if (ret)
359 break;
360 o = parse_object(t->tagged->sha1);
361 if (!o)
362 ret = error("Could not read object %s",
363 sha1_to_hex(t->tagged->sha1));
364 objects[i].item = o;
365 i--;
366 break;
368 case OBJ_TREE:
369 if (rev.shown_one)
370 putchar('\n');
371 printf("%stree %s%s\n\n",
372 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
373 name,
374 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
375 read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
376 show_tree_object, NULL);
377 rev.shown_one = 1;
378 break;
379 case OBJ_COMMIT:
380 rev.pending.nr = rev.pending.alloc = 0;
381 rev.pending.objects = NULL;
382 add_object_array(o, name, &rev.pending);
383 ret = cmd_log_walk(&rev);
384 break;
385 default:
386 ret = error("Unknown type: %d", o->type);
389 free(objects);
390 return ret;
394 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
396 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
398 struct rev_info rev;
400 git_config(git_log_config, NULL);
402 if (diff_use_color_default == -1)
403 diff_use_color_default = git_use_color_default;
405 init_revisions(&rev, prefix);
406 init_reflog_walk(&rev.reflog_info);
407 rev.abbrev_commit = 1;
408 rev.verbose_header = 1;
409 cmd_log_init(argc, argv, prefix, &rev);
412 * This means that we override whatever commit format the user gave
413 * on the cmd line. Sad, but cmd_log_init() currently doesn't
414 * allow us to set a different default.
416 rev.commit_format = CMIT_FMT_ONELINE;
417 rev.use_terminator = 1;
418 rev.always_show_header = 1;
421 * We get called through "git reflog", so unlike the other log
422 * routines, we need to set up our pager manually..
424 setup_pager();
426 return cmd_log_walk(&rev);
429 int cmd_log(int argc, const char **argv, const char *prefix)
431 struct rev_info rev;
433 git_config(git_log_config, NULL);
435 if (diff_use_color_default == -1)
436 diff_use_color_default = git_use_color_default;
438 init_revisions(&rev, prefix);
439 rev.always_show_header = 1;
440 cmd_log_init(argc, argv, prefix, &rev);
441 return cmd_log_walk(&rev);
444 /* format-patch */
446 static const char *fmt_patch_suffix = ".patch";
447 static int numbered = 0;
448 static int auto_number = 1;
450 static char *default_attach = NULL;
452 static char **extra_hdr;
453 static int extra_hdr_nr;
454 static int extra_hdr_alloc;
456 static char **extra_to;
457 static int extra_to_nr;
458 static int extra_to_alloc;
460 static char **extra_cc;
461 static int extra_cc_nr;
462 static int extra_cc_alloc;
464 static void add_header(const char *value)
466 int len = strlen(value);
467 while (len && value[len - 1] == '\n')
468 len--;
469 if (!strncasecmp(value, "to: ", 4)) {
470 ALLOC_GROW(extra_to, extra_to_nr + 1, extra_to_alloc);
471 extra_to[extra_to_nr++] = xstrndup(value + 4, len - 4);
472 return;
474 if (!strncasecmp(value, "cc: ", 4)) {
475 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
476 extra_cc[extra_cc_nr++] = xstrndup(value + 4, len - 4);
477 return;
479 ALLOC_GROW(extra_hdr, extra_hdr_nr + 1, extra_hdr_alloc);
480 extra_hdr[extra_hdr_nr++] = xstrndup(value, len);
483 #define THREAD_SHALLOW 1
484 #define THREAD_DEEP 2
485 static int thread = 0;
486 static int do_signoff = 0;
488 static int git_format_config(const char *var, const char *value, void *cb)
490 if (!strcmp(var, "format.headers")) {
491 if (!value)
492 die("format.headers without value");
493 add_header(value);
494 return 0;
496 if (!strcmp(var, "format.suffix"))
497 return git_config_string(&fmt_patch_suffix, var, value);
498 if (!strcmp(var, "format.cc")) {
499 if (!value)
500 return config_error_nonbool(var);
501 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
502 extra_cc[extra_cc_nr++] = xstrdup(value);
503 return 0;
505 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
506 return 0;
508 if (!strcmp(var, "format.numbered")) {
509 if (value && !strcasecmp(value, "auto")) {
510 auto_number = 1;
511 return 0;
513 numbered = git_config_bool(var, value);
514 auto_number = auto_number && numbered;
515 return 0;
517 if (!strcmp(var, "format.attach")) {
518 if (value && *value)
519 default_attach = xstrdup(value);
520 else
521 default_attach = xstrdup(git_version_string);
522 return 0;
524 if (!strcmp(var, "format.thread")) {
525 if (value && !strcasecmp(value, "deep")) {
526 thread = THREAD_DEEP;
527 return 0;
529 if (value && !strcasecmp(value, "shallow")) {
530 thread = THREAD_SHALLOW;
531 return 0;
533 thread = git_config_bool(var, value) && THREAD_SHALLOW;
534 return 0;
536 if (!strcmp(var, "format.signoff")) {
537 do_signoff = git_config_bool(var, value);
538 return 0;
541 return git_log_config(var, value, cb);
544 static FILE *realstdout = NULL;
545 static const char *output_directory = NULL;
546 static int outdir_offset;
548 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
550 struct strbuf filename = STRBUF_INIT;
551 int suffix_len = strlen(fmt_patch_suffix) + 1;
553 if (output_directory) {
554 strbuf_addstr(&filename, output_directory);
555 if (filename.len >=
556 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
557 return error("name of output directory is too long");
558 if (filename.buf[filename.len - 1] != '/')
559 strbuf_addch(&filename, '/');
562 get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
564 if (!DIFF_OPT_TST(&rev->diffopt, QUIET))
565 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
567 if (freopen(filename.buf, "w", stdout) == NULL)
568 return error("Cannot open patch file %s", filename.buf);
570 strbuf_release(&filename);
571 return 0;
574 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
576 struct rev_info check_rev;
577 struct commit *commit;
578 struct object *o1, *o2;
579 unsigned flags1, flags2;
581 if (rev->pending.nr != 2)
582 die("Need exactly one range.");
584 o1 = rev->pending.objects[0].item;
585 flags1 = o1->flags;
586 o2 = rev->pending.objects[1].item;
587 flags2 = o2->flags;
589 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
590 die("Not a range.");
592 init_patch_ids(ids);
594 /* given a range a..b get all patch ids for b..a */
595 init_revisions(&check_rev, prefix);
596 o1->flags ^= UNINTERESTING;
597 o2->flags ^= UNINTERESTING;
598 add_pending_object(&check_rev, o1, "o1");
599 add_pending_object(&check_rev, o2, "o2");
600 if (prepare_revision_walk(&check_rev))
601 die("revision walk setup failed");
603 while ((commit = get_revision(&check_rev)) != NULL) {
604 /* ignore merges */
605 if (commit->parents && commit->parents->next)
606 continue;
608 add_commit_patch_id(commit, ids);
611 /* reset for next revision walk */
612 clear_commit_marks((struct commit *)o1,
613 SEEN | UNINTERESTING | SHOWN | ADDED);
614 clear_commit_marks((struct commit *)o2,
615 SEEN | UNINTERESTING | SHOWN | ADDED);
616 o1->flags = flags1;
617 o2->flags = flags2;
620 static void gen_message_id(struct rev_info *info, char *base)
622 const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
623 const char *email_start = strrchr(committer, '<');
624 const char *email_end = strrchr(committer, '>');
625 struct strbuf buf = STRBUF_INIT;
626 if (!email_start || !email_end || email_start > email_end - 1)
627 die("Could not extract email from committer identity.");
628 strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
629 (unsigned long) time(NULL),
630 (int)(email_end - email_start - 1), email_start + 1);
631 info->message_id = strbuf_detach(&buf, NULL);
634 static void make_cover_letter(struct rev_info *rev, int use_stdout,
635 int numbered, int numbered_files,
636 struct commit *origin,
637 int nr, struct commit **list, struct commit *head)
639 const char *committer;
640 const char *subject_start = NULL;
641 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
642 const char *msg;
643 const char *extra_headers = rev->extra_headers;
644 struct shortlog log;
645 struct strbuf sb = STRBUF_INIT;
646 int i;
647 const char *encoding = "UTF-8";
648 struct diff_options opts;
649 int need_8bit_cte = 0;
650 struct commit *commit = NULL;
652 if (rev->commit_format != CMIT_FMT_EMAIL)
653 die("Cover letter needs email format");
655 committer = git_committer_info(0);
657 if (!numbered_files) {
659 * We fake a commit for the cover letter so we get the filename
660 * desired.
662 commit = xcalloc(1, sizeof(*commit));
663 commit->buffer = xmalloc(400);
664 snprintf(commit->buffer, 400,
665 "tree 0000000000000000000000000000000000000000\n"
666 "parent %s\n"
667 "author %s\n"
668 "committer %s\n\n"
669 "cover letter\n",
670 sha1_to_hex(head->object.sha1), committer, committer);
673 if (!use_stdout && reopen_stdout(commit, rev))
674 return;
676 if (commit) {
678 free(commit->buffer);
679 free(commit);
682 log_write_email_headers(rev, head, &subject_start, &extra_headers,
683 &need_8bit_cte);
685 for (i = 0; !need_8bit_cte && i < nr; i++)
686 if (has_non_ascii(list[i]->buffer))
687 need_8bit_cte = 1;
689 msg = body;
690 pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
691 encoding);
692 pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
693 encoding, need_8bit_cte);
694 pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
695 printf("%s\n", sb.buf);
697 strbuf_release(&sb);
699 shortlog_init(&log);
700 log.wrap_lines = 1;
701 log.wrap = 72;
702 log.in1 = 2;
703 log.in2 = 4;
704 for (i = 0; i < nr; i++)
705 shortlog_add_commit(&log, list[i]);
707 shortlog_output(&log);
710 * We can only do diffstat with a unique reference point
712 if (!origin)
713 return;
715 memcpy(&opts, &rev->diffopt, sizeof(opts));
716 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
718 diff_setup_done(&opts);
720 diff_tree_sha1(origin->tree->object.sha1,
721 head->tree->object.sha1,
722 "", &opts);
723 diffcore_std(&opts);
724 diff_flush(&opts);
726 printf("\n");
729 static const char *clean_message_id(const char *msg_id)
731 char ch;
732 const char *a, *z, *m;
734 m = msg_id;
735 while ((ch = *m) && (isspace(ch) || (ch == '<')))
736 m++;
737 a = m;
738 z = NULL;
739 while ((ch = *m)) {
740 if (!isspace(ch) && (ch != '>'))
741 z = m;
742 m++;
744 if (!z)
745 die("insane in-reply-to: %s", msg_id);
746 if (++z == m)
747 return a;
748 return xmemdupz(a, z - a);
751 static const char *set_outdir(const char *prefix, const char *output_directory)
753 if (output_directory && is_absolute_path(output_directory))
754 return output_directory;
756 if (!prefix || !*prefix) {
757 if (output_directory)
758 return output_directory;
759 /* The user did not explicitly ask for "./" */
760 outdir_offset = 2;
761 return "./";
764 outdir_offset = strlen(prefix);
765 if (!output_directory)
766 return prefix;
768 return xstrdup(prefix_filename(prefix, outdir_offset,
769 output_directory));
772 static const char * const builtin_format_patch_usage[] = {
773 "git format-patch [options] [<since> | <revision range>]",
774 NULL
777 static int keep_subject = 0;
779 static int keep_callback(const struct option *opt, const char *arg, int unset)
781 ((struct rev_info *)opt->value)->total = -1;
782 keep_subject = 1;
783 return 0;
786 static int subject_prefix = 0;
788 static int subject_prefix_callback(const struct option *opt, const char *arg,
789 int unset)
791 subject_prefix = 1;
792 ((struct rev_info *)opt->value)->subject_prefix = arg;
793 return 0;
796 static int numbered_cmdline_opt = 0;
798 static int numbered_callback(const struct option *opt, const char *arg,
799 int unset)
801 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
802 if (unset)
803 auto_number = 0;
804 return 0;
807 static int no_numbered_callback(const struct option *opt, const char *arg,
808 int unset)
810 return numbered_callback(opt, arg, 1);
813 static int output_directory_callback(const struct option *opt, const char *arg,
814 int unset)
816 const char **dir = (const char **)opt->value;
817 if (*dir)
818 die("Two output directories?");
819 *dir = arg;
820 return 0;
823 static int thread_callback(const struct option *opt, const char *arg, int unset)
825 int *thread = (int *)opt->value;
826 if (unset)
827 *thread = 0;
828 else if (!arg || !strcmp(arg, "shallow"))
829 *thread = THREAD_SHALLOW;
830 else if (!strcmp(arg, "deep"))
831 *thread = THREAD_DEEP;
832 else
833 return 1;
834 return 0;
837 static int attach_callback(const struct option *opt, const char *arg, int unset)
839 struct rev_info *rev = (struct rev_info *)opt->value;
840 if (unset)
841 rev->mime_boundary = NULL;
842 else if (arg)
843 rev->mime_boundary = arg;
844 else
845 rev->mime_boundary = git_version_string;
846 rev->no_inline = unset ? 0 : 1;
847 return 0;
850 static int inline_callback(const struct option *opt, const char *arg, int unset)
852 struct rev_info *rev = (struct rev_info *)opt->value;
853 if (unset)
854 rev->mime_boundary = NULL;
855 else if (arg)
856 rev->mime_boundary = arg;
857 else
858 rev->mime_boundary = git_version_string;
859 rev->no_inline = 0;
860 return 0;
863 static int header_callback(const struct option *opt, const char *arg, int unset)
865 add_header(arg);
866 return 0;
869 static int cc_callback(const struct option *opt, const char *arg, int unset)
871 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
872 extra_cc[extra_cc_nr++] = xstrdup(arg);
873 return 0;
876 int cmd_format_patch(int argc, const char **argv, const char *prefix)
878 struct commit *commit;
879 struct commit **list = NULL;
880 struct rev_info rev;
881 int nr = 0, total, i;
882 int use_stdout = 0;
883 int start_number = -1;
884 int numbered_files = 0; /* _just_ numbers */
885 int ignore_if_in_upstream = 0;
886 int cover_letter = 0;
887 int boundary_count = 0;
888 int no_binary_diff = 0;
889 struct commit *origin = NULL, *head = NULL;
890 const char *in_reply_to = NULL;
891 struct patch_ids ids;
892 char *add_signoff = NULL;
893 struct strbuf buf = STRBUF_INIT;
894 int use_patch_format = 0;
895 const struct option builtin_format_patch_options[] = {
896 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
897 "use [PATCH n/m] even with a single patch",
898 PARSE_OPT_NOARG, numbered_callback },
899 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
900 "use [PATCH] even with multiple patches",
901 PARSE_OPT_NOARG, no_numbered_callback },
902 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
903 OPT_BOOLEAN(0, "stdout", &use_stdout,
904 "print patches to standard out"),
905 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
906 "generate a cover letter"),
907 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
908 "use simple number sequence for output file names"),
909 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
910 "use <sfx> instead of '.patch'"),
911 OPT_INTEGER(0, "start-number", &start_number,
912 "start numbering patches at <n> instead of 1"),
913 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
914 "Use [<prefix>] instead of [PATCH]",
915 PARSE_OPT_NONEG, subject_prefix_callback },
916 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
917 "dir", "store resulting files in <dir>",
918 PARSE_OPT_NONEG, output_directory_callback },
919 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
920 "don't strip/add [PATCH]",
921 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
922 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
923 "don't output binary diffs"),
924 OPT_BOOLEAN('p', NULL, &use_patch_format,
925 "show patch format instead of default (patch + stat)"),
926 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
927 "don't include a patch matching a commit upstream"),
928 OPT_GROUP("Messaging"),
929 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
930 "add email header", PARSE_OPT_NONEG,
931 header_callback },
932 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
933 PARSE_OPT_NONEG, cc_callback },
934 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
935 "make first mail a reply to <message-id>"),
936 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
937 "attach the patch", PARSE_OPT_OPTARG,
938 attach_callback },
939 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
940 "inline the patch",
941 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
942 inline_callback },
943 { OPTION_CALLBACK, 0, "thread", &thread, "style",
944 "enable message threading, styles: shallow, deep",
945 PARSE_OPT_OPTARG, thread_callback },
946 OPT_END()
949 git_config(git_format_config, NULL);
950 init_revisions(&rev, prefix);
951 rev.commit_format = CMIT_FMT_EMAIL;
952 rev.verbose_header = 1;
953 rev.diff = 1;
954 rev.combine_merges = 0;
955 rev.ignore_merges = 1;
956 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
958 rev.subject_prefix = fmt_patch_subject_prefix;
960 if (default_attach) {
961 rev.mime_boundary = default_attach;
962 rev.no_inline = 1;
966 * Parse the arguments before setup_revisions(), or something
967 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
968 * possibly a valid SHA1.
970 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
971 builtin_format_patch_usage,
972 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
973 PARSE_OPT_KEEP_DASHDASH);
975 if (do_signoff) {
976 const char *committer;
977 const char *endpos;
978 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
979 endpos = strchr(committer, '>');
980 if (!endpos)
981 die("bogus committer info %s", committer);
982 add_signoff = xmemdupz(committer, endpos - committer + 1);
985 for (i = 0; i < extra_hdr_nr; i++) {
986 strbuf_addstr(&buf, extra_hdr[i]);
987 strbuf_addch(&buf, '\n');
990 if (extra_to_nr)
991 strbuf_addstr(&buf, "To: ");
992 for (i = 0; i < extra_to_nr; i++) {
993 if (i)
994 strbuf_addstr(&buf, " ");
995 strbuf_addstr(&buf, extra_to[i]);
996 if (i + 1 < extra_to_nr)
997 strbuf_addch(&buf, ',');
998 strbuf_addch(&buf, '\n');
1001 if (extra_cc_nr)
1002 strbuf_addstr(&buf, "Cc: ");
1003 for (i = 0; i < extra_cc_nr; i++) {
1004 if (i)
1005 strbuf_addstr(&buf, " ");
1006 strbuf_addstr(&buf, extra_cc[i]);
1007 if (i + 1 < extra_cc_nr)
1008 strbuf_addch(&buf, ',');
1009 strbuf_addch(&buf, '\n');
1012 rev.extra_headers = strbuf_detach(&buf, NULL);
1014 if (start_number < 0)
1015 start_number = 1;
1018 * If numbered is set solely due to format.numbered in config,
1019 * and it would conflict with --keep-subject (-k) from the
1020 * command line, reset "numbered".
1022 if (numbered && keep_subject && !numbered_cmdline_opt)
1023 numbered = 0;
1025 if (numbered && keep_subject)
1026 die ("-n and -k are mutually exclusive.");
1027 if (keep_subject && subject_prefix)
1028 die ("--subject-prefix and -k are mutually exclusive.");
1030 argc = setup_revisions(argc, argv, &rev, "HEAD");
1031 if (argc > 1)
1032 die ("unrecognized argument: %s", argv[1]);
1034 if (use_patch_format)
1035 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1036 else if (!rev.diffopt.output_format ||
1037 rev.diffopt.output_format == DIFF_FORMAT_PATCH)
1038 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
1040 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1041 DIFF_OPT_SET(&rev.diffopt, BINARY);
1043 if (!use_stdout)
1044 output_directory = set_outdir(prefix, output_directory);
1046 if (output_directory) {
1047 if (use_stdout)
1048 die("standard output, or directory, which one?");
1049 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1050 die_errno("Could not create directory '%s'",
1051 output_directory);
1054 if (rev.pending.nr == 1) {
1055 if (rev.max_count < 0 && !rev.show_root_diff) {
1057 * This is traditional behaviour of "git format-patch
1058 * origin" that prepares what the origin side still
1059 * does not have.
1061 rev.pending.objects[0].item->flags |= UNINTERESTING;
1062 add_head_to_pending(&rev);
1065 * Otherwise, it is "format-patch -22 HEAD", and/or
1066 * "format-patch --root HEAD". The user wants
1067 * get_revision() to do the usual traversal.
1072 * We cannot move this anywhere earlier because we do want to
1073 * know if --root was given explicitly from the comand line.
1075 rev.show_root_diff = 1;
1077 if (cover_letter) {
1078 /* remember the range */
1079 int i;
1080 for (i = 0; i < rev.pending.nr; i++) {
1081 struct object *o = rev.pending.objects[i].item;
1082 if (!(o->flags & UNINTERESTING))
1083 head = (struct commit *)o;
1085 /* We can't generate a cover letter without any patches */
1086 if (!head)
1087 return 0;
1090 if (ignore_if_in_upstream)
1091 get_patch_ids(&rev, &ids, prefix);
1093 if (!use_stdout)
1094 realstdout = xfdopen(xdup(1), "w");
1096 if (prepare_revision_walk(&rev))
1097 die("revision walk setup failed");
1098 rev.boundary = 1;
1099 while ((commit = get_revision(&rev)) != NULL) {
1100 if (commit->object.flags & BOUNDARY) {
1101 boundary_count++;
1102 origin = (boundary_count == 1) ? commit : NULL;
1103 continue;
1106 /* ignore merges */
1107 if (commit->parents && commit->parents->next)
1108 continue;
1110 if (ignore_if_in_upstream &&
1111 has_commit_patch_id(commit, &ids))
1112 continue;
1114 nr++;
1115 list = xrealloc(list, nr * sizeof(list[0]));
1116 list[nr - 1] = commit;
1118 total = nr;
1119 if (!keep_subject && auto_number && total > 1)
1120 numbered = 1;
1121 if (numbered)
1122 rev.total = total + start_number - 1;
1123 if (in_reply_to || thread || cover_letter)
1124 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1125 if (in_reply_to) {
1126 const char *msgid = clean_message_id(in_reply_to);
1127 string_list_append(msgid, rev.ref_message_ids);
1129 rev.numbered_files = numbered_files;
1130 rev.patch_suffix = fmt_patch_suffix;
1131 if (cover_letter) {
1132 if (thread)
1133 gen_message_id(&rev, "cover");
1134 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1135 origin, nr, list, head);
1136 total++;
1137 start_number--;
1139 rev.add_signoff = add_signoff;
1140 while (0 <= --nr) {
1141 int shown;
1142 commit = list[nr];
1143 rev.nr = total - nr + (start_number - 1);
1144 /* Make the second and subsequent mails replies to the first */
1145 if (thread) {
1146 /* Have we already had a message ID? */
1147 if (rev.message_id) {
1149 * For deep threading: make every mail
1150 * a reply to the previous one, no
1151 * matter what other options are set.
1153 * For shallow threading:
1155 * Without --cover-letter and
1156 * --in-reply-to, make every mail a
1157 * reply to the one before.
1159 * With --in-reply-to but no
1160 * --cover-letter, make every mail a
1161 * reply to the <reply-to>.
1163 * With --cover-letter, make every
1164 * mail but the cover letter a reply
1165 * to the cover letter. The cover
1166 * letter is a reply to the
1167 * --in-reply-to, if specified.
1169 if (thread == THREAD_SHALLOW
1170 && rev.ref_message_ids->nr > 0
1171 && (!cover_letter || rev.nr > 1))
1172 free(rev.message_id);
1173 else
1174 string_list_append(rev.message_id,
1175 rev.ref_message_ids);
1177 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1180 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1181 &rev))
1182 die("Failed to create output files");
1183 shown = log_tree_commit(&rev, commit);
1184 free(commit->buffer);
1185 commit->buffer = NULL;
1187 /* We put one extra blank line between formatted
1188 * patches and this flag is used by log-tree code
1189 * to see if it needs to emit a LF before showing
1190 * the log; when using one file per patch, we do
1191 * not want the extra blank line.
1193 if (!use_stdout)
1194 rev.shown_one = 0;
1195 if (shown) {
1196 if (rev.mime_boundary)
1197 printf("\n--%s%s--\n\n\n",
1198 mime_boundary_leader,
1199 rev.mime_boundary);
1200 else
1201 printf("-- \n%s\n\n", git_version_string);
1203 if (!use_stdout)
1204 fclose(stdout);
1206 free(list);
1207 if (ignore_if_in_upstream)
1208 free_patch_ids(&ids);
1209 return 0;
1212 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1214 unsigned char sha1[20];
1215 if (get_sha1(arg, sha1) == 0) {
1216 struct commit *commit = lookup_commit_reference(sha1);
1217 if (commit) {
1218 commit->object.flags |= flags;
1219 add_pending_object(revs, &commit->object, arg);
1220 return 0;
1223 return -1;
1226 static const char cherry_usage[] =
1227 "git cherry [-v] [<upstream> [<head> [<limit>]]]";
1228 int cmd_cherry(int argc, const char **argv, const char *prefix)
1230 struct rev_info revs;
1231 struct patch_ids ids;
1232 struct commit *commit;
1233 struct commit_list *list = NULL;
1234 struct branch *current_branch;
1235 const char *upstream;
1236 const char *head = "HEAD";
1237 const char *limit = NULL;
1238 int verbose = 0;
1240 if (argc > 1 && !strcmp(argv[1], "-v")) {
1241 verbose = 1;
1242 argc--;
1243 argv++;
1246 switch (argc) {
1247 case 4:
1248 limit = argv[3];
1249 /* FALLTHROUGH */
1250 case 3:
1251 head = argv[2];
1252 /* FALLTHROUGH */
1253 case 2:
1254 upstream = argv[1];
1255 break;
1256 default:
1257 current_branch = branch_get(NULL);
1258 if (!current_branch || !current_branch->merge
1259 || !current_branch->merge[0]
1260 || !current_branch->merge[0]->dst) {
1261 fprintf(stderr, "Could not find a tracked"
1262 " remote branch, please"
1263 " specify <upstream> manually.\n");
1264 usage(cherry_usage);
1267 upstream = current_branch->merge[0]->dst;
1270 init_revisions(&revs, prefix);
1271 revs.diff = 1;
1272 revs.combine_merges = 0;
1273 revs.ignore_merges = 1;
1274 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1276 if (add_pending_commit(head, &revs, 0))
1277 die("Unknown commit %s", head);
1278 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1279 die("Unknown commit %s", upstream);
1281 /* Don't say anything if head and upstream are the same. */
1282 if (revs.pending.nr == 2) {
1283 struct object_array_entry *o = revs.pending.objects;
1284 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1285 return 0;
1288 get_patch_ids(&revs, &ids, prefix);
1290 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1291 die("Unknown commit %s", limit);
1293 /* reverse the list of commits */
1294 if (prepare_revision_walk(&revs))
1295 die("revision walk setup failed");
1296 while ((commit = get_revision(&revs)) != NULL) {
1297 /* ignore merges */
1298 if (commit->parents && commit->parents->next)
1299 continue;
1301 commit_list_insert(commit, &list);
1304 while (list) {
1305 char sign = '+';
1307 commit = list->item;
1308 if (has_commit_patch_id(commit, &ids))
1309 sign = '-';
1311 if (verbose) {
1312 struct strbuf buf = STRBUF_INIT;
1313 pretty_print_commit(CMIT_FMT_ONELINE, commit,
1314 &buf, 0, NULL, NULL, 0, 0);
1315 printf("%c %s %s\n", sign,
1316 sha1_to_hex(commit->object.sha1), buf.buf);
1317 strbuf_release(&buf);
1319 else {
1320 printf("%c %s\n", sign,
1321 sha1_to_hex(commit->object.sha1));
1324 list = list->next;
1327 free_patch_ids(&ids);
1328 return 0;