Contribute a script to split a given commit range into topic branches
[git/dscho.git] / builtin-log.c
blobcb0046f8acb3d3d334390b420126742ecd6cc122
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);
54 * Check for -h before setup_revisions(), or "git log -h" will
55 * fail when run without a git directory.
57 if (argc == 2 && !strcmp(argv[1], "-h"))
58 usage(builtin_log_usage);
59 argc = setup_revisions(argc, argv, rev, "HEAD");
61 if (!rev->show_notes_given && !rev->pretty_given)
62 rev->show_notes = 1;
64 if (rev->diffopt.pickaxe || rev->diffopt.filter)
65 rev->always_show_header = 0;
66 if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
67 rev->always_show_header = 0;
68 if (rev->diffopt.nr_paths != 1)
69 usage("git logs can only follow renames on one pathname at a time");
71 for (i = 1; i < argc; i++) {
72 const char *arg = argv[i];
73 if (!strcmp(arg, "--decorate")) {
74 decoration_style = DECORATE_SHORT_REFS;
75 } else if (!prefixcmp(arg, "--decorate=")) {
76 const char *v = skip_prefix(arg, "--decorate=");
77 if (!strcmp(v, "full"))
78 decoration_style = DECORATE_FULL_REFS;
79 else if (!strcmp(v, "short"))
80 decoration_style = DECORATE_SHORT_REFS;
81 else
82 die("invalid --decorate option: %s", arg);
83 } else if (!strcmp(arg, "--source")) {
84 rev->show_source = 1;
85 } else if (!strcmp(arg, "-h")) {
86 usage(builtin_log_usage);
87 } else
88 die("unrecognized argument: %s", arg);
90 if (decoration_style) {
91 rev->show_decorations = 1;
92 load_ref_decorations(decoration_style);
97 * This gives a rough estimate for how many commits we
98 * will print out in the list.
100 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
102 int n = 0;
104 while (list) {
105 struct commit *commit = list->item;
106 unsigned int flags = commit->object.flags;
107 list = list->next;
108 if (!(flags & (TREESAME | UNINTERESTING)))
109 n++;
111 return n;
114 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
116 if (rev->shown_one) {
117 rev->shown_one = 0;
118 if (rev->commit_format != CMIT_FMT_ONELINE)
119 putchar(rev->diffopt.line_termination);
121 printf("Final output: %d %s\n", nr, stage);
124 static struct itimerval early_output_timer;
126 static void log_show_early(struct rev_info *revs, struct commit_list *list)
128 int i = revs->early_output;
129 int show_header = 1;
131 sort_in_topological_order(&list, revs->lifo);
132 while (list && i) {
133 struct commit *commit = list->item;
134 switch (simplify_commit(revs, commit)) {
135 case commit_show:
136 if (show_header) {
137 int n = estimate_commit_count(revs, list);
138 show_early_header(revs, "incomplete", n);
139 show_header = 0;
141 log_tree_commit(revs, commit);
142 i--;
143 break;
144 case commit_ignore:
145 break;
146 case commit_error:
147 return;
149 list = list->next;
152 /* Did we already get enough commits for the early output? */
153 if (!i)
154 return;
157 * ..if no, then repeat it twice a second until we
158 * do.
160 * NOTE! We don't use "it_interval", because if the
161 * reader isn't listening, we want our output to be
162 * throttled by the writing, and not have the timer
163 * trigger every second even if we're blocked on a
164 * reader!
166 early_output_timer.it_value.tv_sec = 0;
167 early_output_timer.it_value.tv_usec = 500000;
168 setitimer(ITIMER_REAL, &early_output_timer, NULL);
171 static void early_output(int signal)
173 show_early_output = log_show_early;
176 static void setup_early_output(struct rev_info *rev)
178 struct sigaction sa;
181 * Set up the signal handler, minimally intrusively:
182 * we only set a single volatile integer word (not
183 * using sigatomic_t - trying to avoid unnecessary
184 * system dependencies and headers), and using
185 * SA_RESTART.
187 memset(&sa, 0, sizeof(sa));
188 sa.sa_handler = early_output;
189 sigemptyset(&sa.sa_mask);
190 sa.sa_flags = SA_RESTART;
191 sigaction(SIGALRM, &sa, NULL);
194 * If we can get the whole output in less than a
195 * tenth of a second, don't even bother doing the
196 * early-output thing..
198 * This is a one-time-only trigger.
200 early_output_timer.it_value.tv_sec = 0;
201 early_output_timer.it_value.tv_usec = 100000;
202 setitimer(ITIMER_REAL, &early_output_timer, NULL);
205 static void finish_early_output(struct rev_info *rev)
207 int n = estimate_commit_count(rev, rev->commits);
208 signal(SIGALRM, SIG_IGN);
209 show_early_header(rev, "done", n);
212 static int cmd_log_walk(struct rev_info *rev)
214 struct commit *commit;
216 if (rev->early_output)
217 setup_early_output(rev);
219 if (prepare_revision_walk(rev))
220 die("revision walk setup failed");
222 if (rev->early_output)
223 finish_early_output(rev);
226 * For --check and --exit-code, the exit code is based on CHECK_FAILED
227 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
228 * retain that state information if replacing rev->diffopt in this loop
230 while ((commit = get_revision(rev)) != NULL) {
231 log_tree_commit(rev, commit);
232 if (!rev->reflog_info) {
233 /* we allow cycles in reflog ancestry */
234 free(commit->buffer);
235 commit->buffer = NULL;
237 free_commit_list(commit->parents);
238 commit->parents = NULL;
240 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
241 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
242 return 02;
244 return diff_result_code(&rev->diffopt, 0);
247 static int git_log_config(const char *var, const char *value, void *cb)
249 if (!strcmp(var, "format.pretty"))
250 return git_config_string(&fmt_pretty, var, value);
251 if (!strcmp(var, "format.subjectprefix"))
252 return git_config_string(&fmt_patch_subject_prefix, var, value);
253 if (!strcmp(var, "log.date"))
254 return git_config_string(&default_date_mode, var, value);
255 if (!strcmp(var, "log.showroot")) {
256 default_show_root = git_config_bool(var, value);
257 return 0;
259 return git_diff_ui_config(var, value, cb);
262 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
264 struct rev_info rev;
266 git_config(git_log_config, NULL);
268 if (diff_use_color_default == -1)
269 diff_use_color_default = git_use_color_default;
271 init_revisions(&rev, prefix);
272 rev.diff = 1;
273 rev.simplify_history = 0;
274 cmd_log_init(argc, argv, prefix, &rev);
275 if (!rev.diffopt.output_format)
276 rev.diffopt.output_format = DIFF_FORMAT_RAW;
277 return cmd_log_walk(&rev);
280 static void show_tagger(char *buf, int len, struct rev_info *rev)
282 struct strbuf out = STRBUF_INIT;
284 pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
285 git_log_output_encoding ?
286 git_log_output_encoding: git_commit_encoding);
287 printf("%s", out.buf);
288 strbuf_release(&out);
291 static int show_object(const unsigned char *sha1, int show_tag_object,
292 struct rev_info *rev)
294 unsigned long size;
295 enum object_type type;
296 char *buf = read_sha1_file(sha1, &type, &size);
297 int offset = 0;
299 if (!buf)
300 return error("Could not read object %s", sha1_to_hex(sha1));
302 if (show_tag_object)
303 while (offset < size && buf[offset] != '\n') {
304 int new_offset = offset + 1;
305 while (new_offset < size && buf[new_offset++] != '\n')
306 ; /* do nothing */
307 if (!prefixcmp(buf + offset, "tagger "))
308 show_tagger(buf + offset + 7,
309 new_offset - offset - 7, rev);
310 offset = new_offset;
313 if (offset < size)
314 fwrite(buf + offset, size - offset, 1, stdout);
315 free(buf);
316 return 0;
319 static int show_tree_object(const unsigned char *sha1,
320 const char *base, int baselen,
321 const char *pathname, unsigned mode, int stage, void *context)
323 int *recursive = context;
324 printf("%06o %s %.*s%s%s\n", mode,
325 find_unique_abbrev(sha1, DEFAULT_ABBREV),
326 baselen, base,
327 pathname, S_ISDIR(mode) ? "/" : "");
328 return *recursive ? READ_TREE_RECURSIVE : 0;
331 int cmd_show(int argc, const char **argv, const char *prefix)
333 struct rev_info rev;
334 struct object_array_entry *objects;
335 int i, count, ret = 0;
336 int tree_recursive = 0;
338 git_config(git_log_config, NULL);
340 if (diff_use_color_default == -1)
341 diff_use_color_default = git_use_color_default;
343 init_revisions(&rev, prefix);
344 rev.diff = 1;
345 rev.combine_merges = 1;
346 rev.dense_combined_merges = 1;
347 rev.always_show_header = 1;
348 rev.ignore_merges = 0;
349 rev.no_walk = 1;
350 for (i = 1; i < argc && strcmp(argv[i], "--"); i++)
351 if (!strcmp(argv[i], "-r")) {
352 tree_recursive = 1;
353 break;
355 cmd_log_init(argc, argv, prefix, &rev);
357 count = rev.pending.nr;
358 objects = rev.pending.objects;
359 for (i = 0; i < count && !ret; i++) {
360 struct object *o = objects[i].item;
361 const char *name = objects[i].name;
362 switch (o->type) {
363 case OBJ_BLOB:
364 ret = show_object(o->sha1, 0, NULL);
365 break;
366 case OBJ_TAG: {
367 struct tag *t = (struct tag *)o;
369 if (rev.shown_one)
370 putchar('\n');
371 printf("%stag %s%s\n",
372 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
373 t->tag,
374 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
375 ret = show_object(o->sha1, 1, &rev);
376 rev.shown_one = 1;
377 if (ret)
378 break;
379 o = parse_object(t->tagged->sha1);
380 if (!o)
381 ret = error("Could not read object %s",
382 sha1_to_hex(t->tagged->sha1));
383 objects[i].item = o;
384 i--;
385 break;
387 case OBJ_TREE:
388 if (rev.shown_one)
389 putchar('\n');
390 printf("%stree %s%s\n\n",
391 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
392 name,
393 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
394 read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
395 show_tree_object, &tree_recursive);
396 rev.shown_one = 1;
397 break;
398 case OBJ_COMMIT:
399 rev.pending.nr = rev.pending.alloc = 0;
400 rev.pending.objects = NULL;
401 add_object_array(o, name, &rev.pending);
402 ret = cmd_log_walk(&rev);
403 break;
404 default:
405 ret = error("Unknown type: %d", o->type);
408 free(objects);
409 return ret;
413 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
415 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
417 struct rev_info rev;
419 git_config(git_log_config, NULL);
421 if (diff_use_color_default == -1)
422 diff_use_color_default = git_use_color_default;
424 init_revisions(&rev, prefix);
425 init_reflog_walk(&rev.reflog_info);
426 rev.abbrev_commit = 1;
427 rev.verbose_header = 1;
428 cmd_log_init(argc, argv, prefix, &rev);
431 * This means that we override whatever commit format the user gave
432 * on the cmd line. Sad, but cmd_log_init() currently doesn't
433 * allow us to set a different default.
435 rev.commit_format = CMIT_FMT_ONELINE;
436 rev.use_terminator = 1;
437 rev.always_show_header = 1;
440 * We get called through "git reflog", so unlike the other log
441 * routines, we need to set up our pager manually..
443 setup_pager();
445 return cmd_log_walk(&rev);
448 int cmd_log(int argc, const char **argv, const char *prefix)
450 struct rev_info rev;
452 git_config(git_log_config, NULL);
454 if (diff_use_color_default == -1)
455 diff_use_color_default = git_use_color_default;
457 init_revisions(&rev, prefix);
458 rev.always_show_header = 1;
459 cmd_log_init(argc, argv, prefix, &rev);
460 return cmd_log_walk(&rev);
463 /* format-patch */
465 static const char *fmt_patch_suffix = ".patch";
466 static int numbered = 0;
467 static int auto_number = 1;
469 static char *default_attach = NULL;
471 static char **extra_hdr;
472 static int extra_hdr_nr;
473 static int extra_hdr_alloc;
475 static char **extra_to;
476 static int extra_to_nr;
477 static int extra_to_alloc;
479 static char **extra_cc;
480 static int extra_cc_nr;
481 static int extra_cc_alloc;
483 static void add_header(const char *value)
485 int len = strlen(value);
486 while (len && value[len - 1] == '\n')
487 len--;
488 if (!strncasecmp(value, "to: ", 4)) {
489 ALLOC_GROW(extra_to, extra_to_nr + 1, extra_to_alloc);
490 extra_to[extra_to_nr++] = xstrndup(value + 4, len - 4);
491 return;
493 if (!strncasecmp(value, "cc: ", 4)) {
494 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
495 extra_cc[extra_cc_nr++] = xstrndup(value + 4, len - 4);
496 return;
498 ALLOC_GROW(extra_hdr, extra_hdr_nr + 1, extra_hdr_alloc);
499 extra_hdr[extra_hdr_nr++] = xstrndup(value, len);
502 #define THREAD_SHALLOW 1
503 #define THREAD_DEEP 2
504 static int thread = 0;
505 static int do_signoff = 0;
507 static int git_format_config(const char *var, const char *value, void *cb)
509 if (!strcmp(var, "format.headers")) {
510 if (!value)
511 die("format.headers without value");
512 add_header(value);
513 return 0;
515 if (!strcmp(var, "format.suffix"))
516 return git_config_string(&fmt_patch_suffix, var, value);
517 if (!strcmp(var, "format.cc")) {
518 if (!value)
519 return config_error_nonbool(var);
520 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
521 extra_cc[extra_cc_nr++] = xstrdup(value);
522 return 0;
524 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
525 return 0;
527 if (!strcmp(var, "format.numbered")) {
528 if (value && !strcasecmp(value, "auto")) {
529 auto_number = 1;
530 return 0;
532 numbered = git_config_bool(var, value);
533 auto_number = auto_number && numbered;
534 return 0;
536 if (!strcmp(var, "format.attach")) {
537 if (value && *value)
538 default_attach = xstrdup(value);
539 else
540 default_attach = xstrdup(git_version_string);
541 return 0;
543 if (!strcmp(var, "format.thread")) {
544 if (value && !strcasecmp(value, "deep")) {
545 thread = THREAD_DEEP;
546 return 0;
548 if (value && !strcasecmp(value, "shallow")) {
549 thread = THREAD_SHALLOW;
550 return 0;
552 thread = git_config_bool(var, value) && THREAD_SHALLOW;
553 return 0;
555 if (!strcmp(var, "format.signoff")) {
556 do_signoff = git_config_bool(var, value);
557 return 0;
560 return git_log_config(var, value, cb);
563 static FILE *realstdout = NULL;
564 static const char *output_directory = NULL;
565 static int outdir_offset;
567 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
569 struct strbuf filename = STRBUF_INIT;
570 int suffix_len = strlen(fmt_patch_suffix) + 1;
572 if (output_directory) {
573 strbuf_addstr(&filename, output_directory);
574 if (filename.len >=
575 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
576 return error("name of output directory is too long");
577 if (filename.buf[filename.len - 1] != '/')
578 strbuf_addch(&filename, '/');
581 get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
583 if (!DIFF_OPT_TST(&rev->diffopt, QUICK))
584 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
586 if (freopen(filename.buf, "w", stdout) == NULL)
587 return error("Cannot open patch file %s", filename.buf);
589 strbuf_release(&filename);
590 return 0;
593 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
595 struct rev_info check_rev;
596 struct commit *commit;
597 struct object *o1, *o2;
598 unsigned flags1, flags2;
600 if (rev->pending.nr != 2)
601 die("Need exactly one range.");
603 o1 = rev->pending.objects[0].item;
604 flags1 = o1->flags;
605 o2 = rev->pending.objects[1].item;
606 flags2 = o2->flags;
608 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
609 die("Not a range.");
611 init_patch_ids(ids);
613 /* given a range a..b get all patch ids for b..a */
614 init_revisions(&check_rev, prefix);
615 o1->flags ^= UNINTERESTING;
616 o2->flags ^= UNINTERESTING;
617 add_pending_object(&check_rev, o1, "o1");
618 add_pending_object(&check_rev, o2, "o2");
619 if (prepare_revision_walk(&check_rev))
620 die("revision walk setup failed");
622 while ((commit = get_revision(&check_rev)) != NULL) {
623 /* ignore merges */
624 if (commit->parents && commit->parents->next)
625 continue;
627 add_commit_patch_id(commit, ids);
630 /* reset for next revision walk */
631 clear_commit_marks((struct commit *)o1,
632 SEEN | UNINTERESTING | SHOWN | ADDED);
633 clear_commit_marks((struct commit *)o2,
634 SEEN | UNINTERESTING | SHOWN | ADDED);
635 o1->flags = flags1;
636 o2->flags = flags2;
639 static void gen_message_id(struct rev_info *info, char *base)
641 const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
642 const char *email_start = strrchr(committer, '<');
643 const char *email_end = strrchr(committer, '>');
644 struct strbuf buf = STRBUF_INIT;
645 if (!email_start || !email_end || email_start > email_end - 1)
646 die("Could not extract email from committer identity.");
647 strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
648 (unsigned long) time(NULL),
649 (int)(email_end - email_start - 1), email_start + 1);
650 info->message_id = strbuf_detach(&buf, NULL);
653 static void make_cover_letter(struct rev_info *rev, int use_stdout,
654 int numbered, int numbered_files,
655 struct commit *origin,
656 int nr, struct commit **list, struct commit *head)
658 const char *committer;
659 const char *subject_start = NULL;
660 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
661 const char *msg;
662 const char *extra_headers = rev->extra_headers;
663 struct shortlog log;
664 struct strbuf sb = STRBUF_INIT;
665 int i;
666 const char *encoding = "UTF-8";
667 struct diff_options opts;
668 int need_8bit_cte = 0;
669 struct commit *commit = NULL;
671 if (rev->commit_format != CMIT_FMT_EMAIL)
672 die("Cover letter needs email format");
674 committer = git_committer_info(0);
676 if (!numbered_files) {
678 * We fake a commit for the cover letter so we get the filename
679 * desired.
681 commit = xcalloc(1, sizeof(*commit));
682 commit->buffer = xmalloc(400);
683 snprintf(commit->buffer, 400,
684 "tree 0000000000000000000000000000000000000000\n"
685 "parent %s\n"
686 "author %s\n"
687 "committer %s\n\n"
688 "cover letter\n",
689 sha1_to_hex(head->object.sha1), committer, committer);
692 if (!use_stdout && reopen_stdout(commit, rev))
693 return;
695 if (commit) {
697 free(commit->buffer);
698 free(commit);
701 log_write_email_headers(rev, head, &subject_start, &extra_headers,
702 &need_8bit_cte);
704 for (i = 0; !need_8bit_cte && i < nr; i++)
705 if (has_non_ascii(list[i]->buffer))
706 need_8bit_cte = 1;
708 msg = body;
709 pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
710 encoding);
711 pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
712 encoding, need_8bit_cte);
713 pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
714 printf("%s\n", sb.buf);
716 strbuf_release(&sb);
718 shortlog_init(&log);
719 log.wrap_lines = 1;
720 log.wrap = 72;
721 log.in1 = 2;
722 log.in2 = 4;
723 for (i = 0; i < nr; i++)
724 shortlog_add_commit(&log, list[i]);
726 shortlog_output(&log);
729 * We can only do diffstat with a unique reference point
731 if (!origin)
732 return;
734 memcpy(&opts, &rev->diffopt, sizeof(opts));
735 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
737 diff_setup_done(&opts);
739 diff_tree_sha1(origin->tree->object.sha1,
740 head->tree->object.sha1,
741 "", &opts);
742 diffcore_std(&opts);
743 diff_flush(&opts);
745 printf("\n");
748 static const char *clean_message_id(const char *msg_id)
750 char ch;
751 const char *a, *z, *m;
753 m = msg_id;
754 while ((ch = *m) && (isspace(ch) || (ch == '<')))
755 m++;
756 a = m;
757 z = NULL;
758 while ((ch = *m)) {
759 if (!isspace(ch) && (ch != '>'))
760 z = m;
761 m++;
763 if (!z)
764 die("insane in-reply-to: %s", msg_id);
765 if (++z == m)
766 return a;
767 return xmemdupz(a, z - a);
770 static const char *set_outdir(const char *prefix, const char *output_directory)
772 if (output_directory && is_absolute_path(output_directory))
773 return output_directory;
775 if (!prefix || !*prefix) {
776 if (output_directory)
777 return output_directory;
778 /* The user did not explicitly ask for "./" */
779 outdir_offset = 2;
780 return "./";
783 outdir_offset = strlen(prefix);
784 if (!output_directory)
785 return prefix;
787 return xstrdup(prefix_filename(prefix, outdir_offset,
788 output_directory));
791 static const char * const builtin_format_patch_usage[] = {
792 "git format-patch [options] [<since> | <revision range>]",
793 NULL
796 static int keep_subject = 0;
798 static int keep_callback(const struct option *opt, const char *arg, int unset)
800 ((struct rev_info *)opt->value)->total = -1;
801 keep_subject = 1;
802 return 0;
805 static int subject_prefix = 0;
807 static int subject_prefix_callback(const struct option *opt, const char *arg,
808 int unset)
810 subject_prefix = 1;
811 ((struct rev_info *)opt->value)->subject_prefix = arg;
812 return 0;
815 static int numbered_cmdline_opt = 0;
817 static int numbered_callback(const struct option *opt, const char *arg,
818 int unset)
820 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
821 if (unset)
822 auto_number = 0;
823 return 0;
826 static int no_numbered_callback(const struct option *opt, const char *arg,
827 int unset)
829 return numbered_callback(opt, arg, 1);
832 static int output_directory_callback(const struct option *opt, const char *arg,
833 int unset)
835 const char **dir = (const char **)opt->value;
836 if (*dir)
837 die("Two output directories?");
838 *dir = arg;
839 return 0;
842 static int thread_callback(const struct option *opt, const char *arg, int unset)
844 int *thread = (int *)opt->value;
845 if (unset)
846 *thread = 0;
847 else if (!arg || !strcmp(arg, "shallow"))
848 *thread = THREAD_SHALLOW;
849 else if (!strcmp(arg, "deep"))
850 *thread = THREAD_DEEP;
851 else
852 return 1;
853 return 0;
856 static int attach_callback(const struct option *opt, const char *arg, int unset)
858 struct rev_info *rev = (struct rev_info *)opt->value;
859 if (unset)
860 rev->mime_boundary = NULL;
861 else if (arg)
862 rev->mime_boundary = arg;
863 else
864 rev->mime_boundary = git_version_string;
865 rev->no_inline = unset ? 0 : 1;
866 return 0;
869 static int inline_callback(const struct option *opt, const char *arg, int unset)
871 struct rev_info *rev = (struct rev_info *)opt->value;
872 if (unset)
873 rev->mime_boundary = NULL;
874 else if (arg)
875 rev->mime_boundary = arg;
876 else
877 rev->mime_boundary = git_version_string;
878 rev->no_inline = 0;
879 return 0;
882 static int header_callback(const struct option *opt, const char *arg, int unset)
884 add_header(arg);
885 return 0;
888 static int cc_callback(const struct option *opt, const char *arg, int unset)
890 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
891 extra_cc[extra_cc_nr++] = xstrdup(arg);
892 return 0;
895 int cmd_format_patch(int argc, const char **argv, const char *prefix)
897 struct commit *commit;
898 struct commit **list = NULL;
899 struct rev_info rev;
900 int nr = 0, total, i;
901 int use_stdout = 0;
902 int start_number = -1;
903 int numbered_files = 0; /* _just_ numbers */
904 int ignore_if_in_upstream = 0;
905 int cover_letter = 0;
906 int boundary_count = 0;
907 int no_binary_diff = 0;
908 struct commit *origin = NULL, *head = NULL;
909 const char *in_reply_to = NULL;
910 struct patch_ids ids;
911 char *add_signoff = NULL;
912 struct strbuf buf = STRBUF_INIT;
913 int use_patch_format = 0;
914 const struct option builtin_format_patch_options[] = {
915 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
916 "use [PATCH n/m] even with a single patch",
917 PARSE_OPT_NOARG, numbered_callback },
918 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
919 "use [PATCH] even with multiple patches",
920 PARSE_OPT_NOARG, no_numbered_callback },
921 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
922 OPT_BOOLEAN(0, "stdout", &use_stdout,
923 "print patches to standard out"),
924 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
925 "generate a cover letter"),
926 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
927 "use simple number sequence for output file names"),
928 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
929 "use <sfx> instead of '.patch'"),
930 OPT_INTEGER(0, "start-number", &start_number,
931 "start numbering patches at <n> instead of 1"),
932 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
933 "Use [<prefix>] instead of [PATCH]",
934 PARSE_OPT_NONEG, subject_prefix_callback },
935 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
936 "dir", "store resulting files in <dir>",
937 PARSE_OPT_NONEG, output_directory_callback },
938 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
939 "don't strip/add [PATCH]",
940 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
941 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
942 "don't output binary diffs"),
943 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
944 "don't include a patch matching a commit upstream"),
945 { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
946 "show patch format instead of default (patch + stat)",
947 PARSE_OPT_NONEG | PARSE_OPT_NOARG },
948 OPT_GROUP("Messaging"),
949 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
950 "add email header", PARSE_OPT_NONEG,
951 header_callback },
952 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
953 PARSE_OPT_NONEG, cc_callback },
954 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
955 "make first mail a reply to <message-id>"),
956 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
957 "attach the patch", PARSE_OPT_OPTARG,
958 attach_callback },
959 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
960 "inline the patch",
961 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
962 inline_callback },
963 { OPTION_CALLBACK, 0, "thread", &thread, "style",
964 "enable message threading, styles: shallow, deep",
965 PARSE_OPT_OPTARG, thread_callback },
966 OPT_END()
969 git_config(git_format_config, NULL);
970 init_revisions(&rev, prefix);
971 rev.commit_format = CMIT_FMT_EMAIL;
972 rev.verbose_header = 1;
973 rev.diff = 1;
974 rev.combine_merges = 0;
975 rev.ignore_merges = 1;
976 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
978 rev.subject_prefix = fmt_patch_subject_prefix;
980 if (default_attach) {
981 rev.mime_boundary = default_attach;
982 rev.no_inline = 1;
986 * Parse the arguments before setup_revisions(), or something
987 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
988 * possibly a valid SHA1.
990 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
991 builtin_format_patch_usage,
992 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
993 PARSE_OPT_KEEP_DASHDASH);
995 if (do_signoff) {
996 const char *committer;
997 const char *endpos;
998 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
999 endpos = strchr(committer, '>');
1000 if (!endpos)
1001 die("bogus committer info %s", committer);
1002 add_signoff = xmemdupz(committer, endpos - committer + 1);
1005 for (i = 0; i < extra_hdr_nr; i++) {
1006 strbuf_addstr(&buf, extra_hdr[i]);
1007 strbuf_addch(&buf, '\n');
1010 if (extra_to_nr)
1011 strbuf_addstr(&buf, "To: ");
1012 for (i = 0; i < extra_to_nr; i++) {
1013 if (i)
1014 strbuf_addstr(&buf, " ");
1015 strbuf_addstr(&buf, extra_to[i]);
1016 if (i + 1 < extra_to_nr)
1017 strbuf_addch(&buf, ',');
1018 strbuf_addch(&buf, '\n');
1021 if (extra_cc_nr)
1022 strbuf_addstr(&buf, "Cc: ");
1023 for (i = 0; i < extra_cc_nr; i++) {
1024 if (i)
1025 strbuf_addstr(&buf, " ");
1026 strbuf_addstr(&buf, extra_cc[i]);
1027 if (i + 1 < extra_cc_nr)
1028 strbuf_addch(&buf, ',');
1029 strbuf_addch(&buf, '\n');
1032 rev.extra_headers = strbuf_detach(&buf, NULL);
1034 if (start_number < 0)
1035 start_number = 1;
1038 * If numbered is set solely due to format.numbered in config,
1039 * and it would conflict with --keep-subject (-k) from the
1040 * command line, reset "numbered".
1042 if (numbered && keep_subject && !numbered_cmdline_opt)
1043 numbered = 0;
1045 if (numbered && keep_subject)
1046 die ("-n and -k are mutually exclusive.");
1047 if (keep_subject && subject_prefix)
1048 die ("--subject-prefix and -k are mutually exclusive.");
1050 argc = setup_revisions(argc, argv, &rev, "HEAD");
1051 if (argc > 1)
1052 die ("unrecognized argument: %s", argv[1]);
1054 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1055 die("--name-only does not make sense");
1056 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1057 die("--name-status does not make sense");
1058 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1059 die("--check does not make sense");
1061 if (!use_patch_format &&
1062 (!rev.diffopt.output_format ||
1063 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1064 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1066 /* Always generate a patch */
1067 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1069 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1070 DIFF_OPT_SET(&rev.diffopt, BINARY);
1072 if (!use_stdout)
1073 output_directory = set_outdir(prefix, output_directory);
1075 if (output_directory) {
1076 if (use_stdout)
1077 die("standard output, or directory, which one?");
1078 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1079 die_errno("Could not create directory '%s'",
1080 output_directory);
1083 if (rev.pending.nr == 1) {
1084 if (rev.max_count < 0 && !rev.show_root_diff) {
1086 * This is traditional behaviour of "git format-patch
1087 * origin" that prepares what the origin side still
1088 * does not have.
1090 rev.pending.objects[0].item->flags |= UNINTERESTING;
1091 add_head_to_pending(&rev);
1094 * Otherwise, it is "format-patch -22 HEAD", and/or
1095 * "format-patch --root HEAD". The user wants
1096 * get_revision() to do the usual traversal.
1101 * We cannot move this anywhere earlier because we do want to
1102 * know if --root was given explicitly from the comand line.
1104 rev.show_root_diff = 1;
1106 if (cover_letter) {
1107 /* remember the range */
1108 int i;
1109 for (i = 0; i < rev.pending.nr; i++) {
1110 struct object *o = rev.pending.objects[i].item;
1111 if (!(o->flags & UNINTERESTING))
1112 head = (struct commit *)o;
1114 /* We can't generate a cover letter without any patches */
1115 if (!head)
1116 return 0;
1119 if (ignore_if_in_upstream)
1120 get_patch_ids(&rev, &ids, prefix);
1122 if (!use_stdout)
1123 realstdout = xfdopen(xdup(1), "w");
1125 if (prepare_revision_walk(&rev))
1126 die("revision walk setup failed");
1127 rev.boundary = 1;
1128 while ((commit = get_revision(&rev)) != NULL) {
1129 if (commit->object.flags & BOUNDARY) {
1130 boundary_count++;
1131 origin = (boundary_count == 1) ? commit : NULL;
1132 continue;
1135 /* ignore merges */
1136 if (commit->parents && commit->parents->next)
1137 continue;
1139 if (ignore_if_in_upstream &&
1140 has_commit_patch_id(commit, &ids))
1141 continue;
1143 nr++;
1144 list = xrealloc(list, nr * sizeof(list[0]));
1145 list[nr - 1] = commit;
1147 total = nr;
1148 if (!keep_subject && auto_number && total > 1)
1149 numbered = 1;
1150 if (numbered)
1151 rev.total = total + start_number - 1;
1152 if (in_reply_to || thread || cover_letter)
1153 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1154 if (in_reply_to) {
1155 const char *msgid = clean_message_id(in_reply_to);
1156 string_list_append(msgid, rev.ref_message_ids);
1158 rev.numbered_files = numbered_files;
1159 rev.patch_suffix = fmt_patch_suffix;
1160 if (cover_letter) {
1161 if (thread)
1162 gen_message_id(&rev, "cover");
1163 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1164 origin, nr, list, head);
1165 total++;
1166 start_number--;
1168 rev.add_signoff = add_signoff;
1169 while (0 <= --nr) {
1170 int shown;
1171 commit = list[nr];
1172 rev.nr = total - nr + (start_number - 1);
1173 /* Make the second and subsequent mails replies to the first */
1174 if (thread) {
1175 /* Have we already had a message ID? */
1176 if (rev.message_id) {
1178 * For deep threading: make every mail
1179 * a reply to the previous one, no
1180 * matter what other options are set.
1182 * For shallow threading:
1184 * Without --cover-letter and
1185 * --in-reply-to, make every mail a
1186 * reply to the one before.
1188 * With --in-reply-to but no
1189 * --cover-letter, make every mail a
1190 * reply to the <reply-to>.
1192 * With --cover-letter, make every
1193 * mail but the cover letter a reply
1194 * to the cover letter. The cover
1195 * letter is a reply to the
1196 * --in-reply-to, if specified.
1198 if (thread == THREAD_SHALLOW
1199 && rev.ref_message_ids->nr > 0
1200 && (!cover_letter || rev.nr > 1))
1201 free(rev.message_id);
1202 else
1203 string_list_append(rev.message_id,
1204 rev.ref_message_ids);
1206 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1209 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1210 &rev))
1211 die("Failed to create output files");
1212 shown = log_tree_commit(&rev, commit);
1213 free(commit->buffer);
1214 commit->buffer = NULL;
1216 /* We put one extra blank line between formatted
1217 * patches and this flag is used by log-tree code
1218 * to see if it needs to emit a LF before showing
1219 * the log; when using one file per patch, we do
1220 * not want the extra blank line.
1222 if (!use_stdout)
1223 rev.shown_one = 0;
1224 if (shown) {
1225 if (rev.mime_boundary)
1226 printf("\n--%s%s--\n\n\n",
1227 mime_boundary_leader,
1228 rev.mime_boundary);
1229 else
1230 printf("-- \n%s\n\n", git_version_string);
1232 if (!use_stdout)
1233 fclose(stdout);
1235 free(list);
1236 if (ignore_if_in_upstream)
1237 free_patch_ids(&ids);
1238 return 0;
1241 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1243 unsigned char sha1[20];
1244 if (get_sha1(arg, sha1) == 0) {
1245 struct commit *commit = lookup_commit_reference(sha1);
1246 if (commit) {
1247 commit->object.flags |= flags;
1248 add_pending_object(revs, &commit->object, arg);
1249 return 0;
1252 return -1;
1255 static const char cherry_usage[] =
1256 "git cherry [-v] [<upstream> [<head> [<limit>]]]";
1257 int cmd_cherry(int argc, const char **argv, const char *prefix)
1259 struct rev_info revs;
1260 struct patch_ids ids;
1261 struct commit *commit;
1262 struct commit_list *list = NULL;
1263 struct branch *current_branch;
1264 const char *upstream;
1265 const char *head = "HEAD";
1266 const char *limit = NULL;
1267 int verbose = 0;
1269 if (argc > 1 && !strcmp(argv[1], "-v")) {
1270 verbose = 1;
1271 argc--;
1272 argv++;
1275 if (argc > 1 && !strcmp(argv[1], "-h"))
1276 usage(cherry_usage);
1278 switch (argc) {
1279 case 4:
1280 limit = argv[3];
1281 /* FALLTHROUGH */
1282 case 3:
1283 head = argv[2];
1284 /* FALLTHROUGH */
1285 case 2:
1286 upstream = argv[1];
1287 break;
1288 default:
1289 current_branch = branch_get(NULL);
1290 if (!current_branch || !current_branch->merge
1291 || !current_branch->merge[0]
1292 || !current_branch->merge[0]->dst) {
1293 fprintf(stderr, "Could not find a tracked"
1294 " remote branch, please"
1295 " specify <upstream> manually.\n");
1296 usage(cherry_usage);
1299 upstream = current_branch->merge[0]->dst;
1302 init_revisions(&revs, prefix);
1303 revs.diff = 1;
1304 revs.combine_merges = 0;
1305 revs.ignore_merges = 1;
1306 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1308 if (add_pending_commit(head, &revs, 0))
1309 die("Unknown commit %s", head);
1310 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1311 die("Unknown commit %s", upstream);
1313 /* Don't say anything if head and upstream are the same. */
1314 if (revs.pending.nr == 2) {
1315 struct object_array_entry *o = revs.pending.objects;
1316 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1317 return 0;
1320 get_patch_ids(&revs, &ids, prefix);
1322 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1323 die("Unknown commit %s", limit);
1325 /* reverse the list of commits */
1326 if (prepare_revision_walk(&revs))
1327 die("revision walk setup failed");
1328 while ((commit = get_revision(&revs)) != NULL) {
1329 /* ignore merges */
1330 if (commit->parents && commit->parents->next)
1331 continue;
1333 commit_list_insert(commit, &list);
1336 while (list) {
1337 char sign = '+';
1339 commit = list->item;
1340 if (has_commit_patch_id(commit, &ids))
1341 sign = '-';
1343 if (verbose) {
1344 struct strbuf buf = STRBUF_INIT;
1345 struct pretty_print_context ctx = {0};
1346 pretty_print_commit(CMIT_FMT_ONELINE, commit,
1347 &buf, &ctx);
1348 printf("%c %s %s\n", sign,
1349 sha1_to_hex(commit->object.sha1), buf.buf);
1350 strbuf_release(&buf);
1352 else {
1353 printf("%c %s\n", sign,
1354 sha1_to_hex(commit->object.sha1));
1357 list = list->next;
1360 free_patch_ids(&ids);
1361 return 0;