builtin-apply.c: get rid of an unnecessary use of temporary array
[git/spearce.git] / builtin-log.c
blob25e21ed41534c8c3067c2e0d5afe4284faa2881a
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 const struct option builtin_format_patch_options[] = {
895 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
896 "use [PATCH n/m] even with a single patch",
897 PARSE_OPT_NOARG, numbered_callback },
898 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
899 "use [PATCH] even with multiple patches",
900 PARSE_OPT_NOARG, no_numbered_callback },
901 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
902 OPT_BOOLEAN(0, "stdout", &use_stdout,
903 "print patches to standard out"),
904 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
905 "generate a cover letter"),
906 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
907 "use simple number sequence for output file names"),
908 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
909 "use <sfx> instead of '.patch'"),
910 OPT_INTEGER(0, "start-number", &start_number,
911 "start numbering patches at <n> instead of 1"),
912 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
913 "Use [<prefix>] instead of [PATCH]",
914 PARSE_OPT_NONEG, subject_prefix_callback },
915 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
916 "dir", "store resulting files in <dir>",
917 PARSE_OPT_NONEG, output_directory_callback },
918 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
919 "don't strip/add [PATCH]",
920 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
921 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
922 "don't output binary diffs"),
923 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
924 "don't include a patch matching a commit upstream"),
925 OPT_GROUP("Messaging"),
926 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
927 "add email header", PARSE_OPT_NONEG,
928 header_callback },
929 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
930 PARSE_OPT_NONEG, cc_callback },
931 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
932 "make first mail a reply to <message-id>"),
933 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
934 "attach the patch", PARSE_OPT_OPTARG,
935 attach_callback },
936 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
937 "inline the patch",
938 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
939 inline_callback },
940 { OPTION_CALLBACK, 0, "thread", &thread, "style",
941 "enable message threading, styles: shallow, deep",
942 PARSE_OPT_OPTARG, thread_callback },
943 OPT_END()
946 git_config(git_format_config, NULL);
947 init_revisions(&rev, prefix);
948 rev.commit_format = CMIT_FMT_EMAIL;
949 rev.verbose_header = 1;
950 rev.diff = 1;
951 rev.combine_merges = 0;
952 rev.ignore_merges = 1;
953 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
955 rev.subject_prefix = fmt_patch_subject_prefix;
957 if (default_attach) {
958 rev.mime_boundary = default_attach;
959 rev.no_inline = 1;
963 * Parse the arguments before setup_revisions(), or something
964 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
965 * possibly a valid SHA1.
967 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
968 builtin_format_patch_usage,
969 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN);
971 if (do_signoff) {
972 const char *committer;
973 const char *endpos;
974 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
975 endpos = strchr(committer, '>');
976 if (!endpos)
977 die("bogus committer info %s", committer);
978 add_signoff = xmemdupz(committer, endpos - committer + 1);
981 for (i = 0; i < extra_hdr_nr; i++) {
982 strbuf_addstr(&buf, extra_hdr[i]);
983 strbuf_addch(&buf, '\n');
986 if (extra_to_nr)
987 strbuf_addstr(&buf, "To: ");
988 for (i = 0; i < extra_to_nr; i++) {
989 if (i)
990 strbuf_addstr(&buf, " ");
991 strbuf_addstr(&buf, extra_to[i]);
992 if (i + 1 < extra_to_nr)
993 strbuf_addch(&buf, ',');
994 strbuf_addch(&buf, '\n');
997 if (extra_cc_nr)
998 strbuf_addstr(&buf, "Cc: ");
999 for (i = 0; i < extra_cc_nr; i++) {
1000 if (i)
1001 strbuf_addstr(&buf, " ");
1002 strbuf_addstr(&buf, extra_cc[i]);
1003 if (i + 1 < extra_cc_nr)
1004 strbuf_addch(&buf, ',');
1005 strbuf_addch(&buf, '\n');
1008 rev.extra_headers = strbuf_detach(&buf, NULL);
1010 if (start_number < 0)
1011 start_number = 1;
1014 * If numbered is set solely due to format.numbered in config,
1015 * and it would conflict with --keep-subject (-k) from the
1016 * command line, reset "numbered".
1018 if (numbered && keep_subject && !numbered_cmdline_opt)
1019 numbered = 0;
1021 if (numbered && keep_subject)
1022 die ("-n and -k are mutually exclusive.");
1023 if (keep_subject && subject_prefix)
1024 die ("--subject-prefix and -k are mutually exclusive.");
1026 argc = setup_revisions(argc, argv, &rev, "HEAD");
1027 if (argc > 1)
1028 die ("unrecognized argument: %s", argv[1]);
1030 if (!rev.diffopt.output_format
1031 || rev.diffopt.output_format == DIFF_FORMAT_PATCH)
1032 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
1034 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1035 DIFF_OPT_SET(&rev.diffopt, BINARY);
1037 if (!use_stdout)
1038 output_directory = set_outdir(prefix, output_directory);
1040 if (output_directory) {
1041 if (use_stdout)
1042 die("standard output, or directory, which one?");
1043 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1044 die_errno("Could not create directory '%s'",
1045 output_directory);
1048 if (rev.pending.nr == 1) {
1049 if (rev.max_count < 0 && !rev.show_root_diff) {
1051 * This is traditional behaviour of "git format-patch
1052 * origin" that prepares what the origin side still
1053 * does not have.
1055 rev.pending.objects[0].item->flags |= UNINTERESTING;
1056 add_head_to_pending(&rev);
1059 * Otherwise, it is "format-patch -22 HEAD", and/or
1060 * "format-patch --root HEAD". The user wants
1061 * get_revision() to do the usual traversal.
1066 * We cannot move this anywhere earlier because we do want to
1067 * know if --root was given explicitly from the comand line.
1069 rev.show_root_diff = 1;
1071 if (cover_letter) {
1072 /* remember the range */
1073 int i;
1074 for (i = 0; i < rev.pending.nr; i++) {
1075 struct object *o = rev.pending.objects[i].item;
1076 if (!(o->flags & UNINTERESTING))
1077 head = (struct commit *)o;
1079 /* We can't generate a cover letter without any patches */
1080 if (!head)
1081 return 0;
1084 if (ignore_if_in_upstream)
1085 get_patch_ids(&rev, &ids, prefix);
1087 if (!use_stdout)
1088 realstdout = xfdopen(xdup(1), "w");
1090 if (prepare_revision_walk(&rev))
1091 die("revision walk setup failed");
1092 rev.boundary = 1;
1093 while ((commit = get_revision(&rev)) != NULL) {
1094 if (commit->object.flags & BOUNDARY) {
1095 boundary_count++;
1096 origin = (boundary_count == 1) ? commit : NULL;
1097 continue;
1100 /* ignore merges */
1101 if (commit->parents && commit->parents->next)
1102 continue;
1104 if (ignore_if_in_upstream &&
1105 has_commit_patch_id(commit, &ids))
1106 continue;
1108 nr++;
1109 list = xrealloc(list, nr * sizeof(list[0]));
1110 list[nr - 1] = commit;
1112 total = nr;
1113 if (!keep_subject && auto_number && total > 1)
1114 numbered = 1;
1115 if (numbered)
1116 rev.total = total + start_number - 1;
1117 if (in_reply_to || thread || cover_letter)
1118 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1119 if (in_reply_to) {
1120 const char *msgid = clean_message_id(in_reply_to);
1121 string_list_append(msgid, rev.ref_message_ids);
1123 rev.numbered_files = numbered_files;
1124 rev.patch_suffix = fmt_patch_suffix;
1125 if (cover_letter) {
1126 if (thread)
1127 gen_message_id(&rev, "cover");
1128 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1129 origin, nr, list, head);
1130 total++;
1131 start_number--;
1133 rev.add_signoff = add_signoff;
1134 while (0 <= --nr) {
1135 int shown;
1136 commit = list[nr];
1137 rev.nr = total - nr + (start_number - 1);
1138 /* Make the second and subsequent mails replies to the first */
1139 if (thread) {
1140 /* Have we already had a message ID? */
1141 if (rev.message_id) {
1143 * For deep threading: make every mail
1144 * a reply to the previous one, no
1145 * matter what other options are set.
1147 * For shallow threading:
1149 * Without --cover-letter and
1150 * --in-reply-to, make every mail a
1151 * reply to the one before.
1153 * With --in-reply-to but no
1154 * --cover-letter, make every mail a
1155 * reply to the <reply-to>.
1157 * With --cover-letter, make every
1158 * mail but the cover letter a reply
1159 * to the cover letter. The cover
1160 * letter is a reply to the
1161 * --in-reply-to, if specified.
1163 if (thread == THREAD_SHALLOW
1164 && rev.ref_message_ids->nr > 0
1165 && (!cover_letter || rev.nr > 1))
1166 free(rev.message_id);
1167 else
1168 string_list_append(rev.message_id,
1169 rev.ref_message_ids);
1171 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1174 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1175 &rev))
1176 die("Failed to create output files");
1177 shown = log_tree_commit(&rev, commit);
1178 free(commit->buffer);
1179 commit->buffer = NULL;
1181 /* We put one extra blank line between formatted
1182 * patches and this flag is used by log-tree code
1183 * to see if it needs to emit a LF before showing
1184 * the log; when using one file per patch, we do
1185 * not want the extra blank line.
1187 if (!use_stdout)
1188 rev.shown_one = 0;
1189 if (shown) {
1190 if (rev.mime_boundary)
1191 printf("\n--%s%s--\n\n\n",
1192 mime_boundary_leader,
1193 rev.mime_boundary);
1194 else
1195 printf("-- \n%s\n\n", git_version_string);
1197 if (!use_stdout)
1198 fclose(stdout);
1200 free(list);
1201 if (ignore_if_in_upstream)
1202 free_patch_ids(&ids);
1203 return 0;
1206 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1208 unsigned char sha1[20];
1209 if (get_sha1(arg, sha1) == 0) {
1210 struct commit *commit = lookup_commit_reference(sha1);
1211 if (commit) {
1212 commit->object.flags |= flags;
1213 add_pending_object(revs, &commit->object, arg);
1214 return 0;
1217 return -1;
1220 static const char cherry_usage[] =
1221 "git cherry [-v] [<upstream> [<head> [<limit>]]]";
1222 int cmd_cherry(int argc, const char **argv, const char *prefix)
1224 struct rev_info revs;
1225 struct patch_ids ids;
1226 struct commit *commit;
1227 struct commit_list *list = NULL;
1228 struct branch *current_branch;
1229 const char *upstream;
1230 const char *head = "HEAD";
1231 const char *limit = NULL;
1232 int verbose = 0;
1234 if (argc > 1 && !strcmp(argv[1], "-v")) {
1235 verbose = 1;
1236 argc--;
1237 argv++;
1240 switch (argc) {
1241 case 4:
1242 limit = argv[3];
1243 /* FALLTHROUGH */
1244 case 3:
1245 head = argv[2];
1246 /* FALLTHROUGH */
1247 case 2:
1248 upstream = argv[1];
1249 break;
1250 default:
1251 current_branch = branch_get(NULL);
1252 if (!current_branch || !current_branch->merge
1253 || !current_branch->merge[0]
1254 || !current_branch->merge[0]->dst) {
1255 fprintf(stderr, "Could not find a tracked"
1256 " remote branch, please"
1257 " specify <upstream> manually.\n");
1258 usage(cherry_usage);
1261 upstream = current_branch->merge[0]->dst;
1264 init_revisions(&revs, prefix);
1265 revs.diff = 1;
1266 revs.combine_merges = 0;
1267 revs.ignore_merges = 1;
1268 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1270 if (add_pending_commit(head, &revs, 0))
1271 die("Unknown commit %s", head);
1272 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1273 die("Unknown commit %s", upstream);
1275 /* Don't say anything if head and upstream are the same. */
1276 if (revs.pending.nr == 2) {
1277 struct object_array_entry *o = revs.pending.objects;
1278 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1279 return 0;
1282 get_patch_ids(&revs, &ids, prefix);
1284 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1285 die("Unknown commit %s", limit);
1287 /* reverse the list of commits */
1288 if (prepare_revision_walk(&revs))
1289 die("revision walk setup failed");
1290 while ((commit = get_revision(&revs)) != NULL) {
1291 /* ignore merges */
1292 if (commit->parents && commit->parents->next)
1293 continue;
1295 commit_list_insert(commit, &list);
1298 while (list) {
1299 char sign = '+';
1301 commit = list->item;
1302 if (has_commit_patch_id(commit, &ids))
1303 sign = '-';
1305 if (verbose) {
1306 struct strbuf buf = STRBUF_INIT;
1307 pretty_print_commit(CMIT_FMT_ONELINE, commit,
1308 &buf, 0, NULL, NULL, 0, 0);
1309 printf("%c %s %s\n", sign,
1310 sha1_to_hex(commit->object.sha1), buf.buf);
1311 strbuf_release(&buf);
1313 else {
1314 printf("%c %s\n", sign,
1315 sha1_to_hex(commit->object.sha1));
1318 list = list->next;
1321 free_patch_ids(&ids);
1322 return 0;