fmt-merge-msg: remove custom string_list implementation
[git.git] / builtin / log.c
bloba8dd8c989c5a135e14c6fc06ea3b23f4f0cd0bec
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, struct setup_revision_opt *opt)
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, opt);
61 if (!rev->show_notes_given && !rev->pretty_given)
62 rev->show_notes = 1;
63 if (rev->show_notes)
64 init_display_notes(&rev->notes_opt);
66 if (rev->diffopt.pickaxe || rev->diffopt.filter)
67 rev->always_show_header = 0;
68 if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
69 rev->always_show_header = 0;
70 if (rev->diffopt.nr_paths != 1)
71 usage("git logs can only follow renames on one pathname at a time");
73 for (i = 1; i < argc; i++) {
74 const char *arg = argv[i];
75 if (!strcmp(arg, "--decorate")) {
76 decoration_style = DECORATE_SHORT_REFS;
77 } else if (!prefixcmp(arg, "--decorate=")) {
78 const char *v = skip_prefix(arg, "--decorate=");
79 if (!strcmp(v, "full"))
80 decoration_style = DECORATE_FULL_REFS;
81 else if (!strcmp(v, "short"))
82 decoration_style = DECORATE_SHORT_REFS;
83 else
84 die("invalid --decorate option: %s", arg);
85 } else if (!strcmp(arg, "--source")) {
86 rev->show_source = 1;
87 } else if (!strcmp(arg, "-h")) {
88 usage(builtin_log_usage);
89 } else
90 die("unrecognized argument: %s", arg);
92 if (decoration_style) {
93 rev->show_decorations = 1;
94 load_ref_decorations(decoration_style);
99 * This gives a rough estimate for how many commits we
100 * will print out in the list.
102 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
104 int n = 0;
106 while (list) {
107 struct commit *commit = list->item;
108 unsigned int flags = commit->object.flags;
109 list = list->next;
110 if (!(flags & (TREESAME | UNINTERESTING)))
111 n++;
113 return n;
116 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
118 if (rev->shown_one) {
119 rev->shown_one = 0;
120 if (rev->commit_format != CMIT_FMT_ONELINE)
121 putchar(rev->diffopt.line_termination);
123 printf("Final output: %d %s\n", nr, stage);
126 static struct itimerval early_output_timer;
128 static void log_show_early(struct rev_info *revs, struct commit_list *list)
130 int i = revs->early_output;
131 int show_header = 1;
133 sort_in_topological_order(&list, revs->lifo);
134 while (list && i) {
135 struct commit *commit = list->item;
136 switch (simplify_commit(revs, commit)) {
137 case commit_show:
138 if (show_header) {
139 int n = estimate_commit_count(revs, list);
140 show_early_header(revs, "incomplete", n);
141 show_header = 0;
143 log_tree_commit(revs, commit);
144 i--;
145 break;
146 case commit_ignore:
147 break;
148 case commit_error:
149 return;
151 list = list->next;
154 /* Did we already get enough commits for the early output? */
155 if (!i)
156 return;
159 * ..if no, then repeat it twice a second until we
160 * do.
162 * NOTE! We don't use "it_interval", because if the
163 * reader isn't listening, we want our output to be
164 * throttled by the writing, and not have the timer
165 * trigger every second even if we're blocked on a
166 * reader!
168 early_output_timer.it_value.tv_sec = 0;
169 early_output_timer.it_value.tv_usec = 500000;
170 setitimer(ITIMER_REAL, &early_output_timer, NULL);
173 static void early_output(int signal)
175 show_early_output = log_show_early;
178 static void setup_early_output(struct rev_info *rev)
180 struct sigaction sa;
183 * Set up the signal handler, minimally intrusively:
184 * we only set a single volatile integer word (not
185 * using sigatomic_t - trying to avoid unnecessary
186 * system dependencies and headers), and using
187 * SA_RESTART.
189 memset(&sa, 0, sizeof(sa));
190 sa.sa_handler = early_output;
191 sigemptyset(&sa.sa_mask);
192 sa.sa_flags = SA_RESTART;
193 sigaction(SIGALRM, &sa, NULL);
196 * If we can get the whole output in less than a
197 * tenth of a second, don't even bother doing the
198 * early-output thing..
200 * This is a one-time-only trigger.
202 early_output_timer.it_value.tv_sec = 0;
203 early_output_timer.it_value.tv_usec = 100000;
204 setitimer(ITIMER_REAL, &early_output_timer, NULL);
207 static void finish_early_output(struct rev_info *rev)
209 int n = estimate_commit_count(rev, rev->commits);
210 signal(SIGALRM, SIG_IGN);
211 show_early_header(rev, "done", n);
214 static int cmd_log_walk(struct rev_info *rev)
216 struct commit *commit;
218 if (rev->early_output)
219 setup_early_output(rev);
221 if (prepare_revision_walk(rev))
222 die("revision walk setup failed");
224 if (rev->early_output)
225 finish_early_output(rev);
228 * For --check and --exit-code, the exit code is based on CHECK_FAILED
229 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
230 * retain that state information if replacing rev->diffopt in this loop
232 while ((commit = get_revision(rev)) != NULL) {
233 log_tree_commit(rev, commit);
234 if (!rev->reflog_info) {
235 /* we allow cycles in reflog ancestry */
236 free(commit->buffer);
237 commit->buffer = NULL;
239 free_commit_list(commit->parents);
240 commit->parents = NULL;
242 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
243 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
244 return 02;
246 return diff_result_code(&rev->diffopt, 0);
249 static int git_log_config(const char *var, const char *value, void *cb)
251 if (!strcmp(var, "format.pretty"))
252 return git_config_string(&fmt_pretty, var, value);
253 if (!strcmp(var, "format.subjectprefix"))
254 return git_config_string(&fmt_patch_subject_prefix, var, value);
255 if (!strcmp(var, "log.date"))
256 return git_config_string(&default_date_mode, var, value);
257 if (!strcmp(var, "log.showroot")) {
258 default_show_root = git_config_bool(var, value);
259 return 0;
261 return git_diff_ui_config(var, value, cb);
264 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
266 struct rev_info rev;
267 struct setup_revision_opt opt;
269 git_config(git_log_config, NULL);
271 if (diff_use_color_default == -1)
272 diff_use_color_default = git_use_color_default;
274 init_revisions(&rev, prefix);
275 rev.diff = 1;
276 rev.simplify_history = 0;
277 memset(&opt, 0, sizeof(opt));
278 opt.def = "HEAD";
279 cmd_log_init(argc, argv, prefix, &rev, &opt);
280 if (!rev.diffopt.output_format)
281 rev.diffopt.output_format = DIFF_FORMAT_RAW;
282 return cmd_log_walk(&rev);
285 static void show_tagger(char *buf, int len, struct rev_info *rev)
287 struct strbuf out = STRBUF_INIT;
289 pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
290 git_log_output_encoding ?
291 git_log_output_encoding: git_commit_encoding);
292 printf("%s", out.buf);
293 strbuf_release(&out);
296 static int show_object(const unsigned char *sha1, int show_tag_object,
297 struct rev_info *rev)
299 unsigned long size;
300 enum object_type type;
301 char *buf = read_sha1_file(sha1, &type, &size);
302 int offset = 0;
304 if (!buf)
305 return error("Could not read object %s", sha1_to_hex(sha1));
307 if (show_tag_object)
308 while (offset < size && buf[offset] != '\n') {
309 int new_offset = offset + 1;
310 while (new_offset < size && buf[new_offset++] != '\n')
311 ; /* do nothing */
312 if (!prefixcmp(buf + offset, "tagger "))
313 show_tagger(buf + offset + 7,
314 new_offset - offset - 7, rev);
315 offset = new_offset;
318 if (offset < size)
319 fwrite(buf + offset, size - offset, 1, stdout);
320 free(buf);
321 return 0;
324 static int show_tree_object(const unsigned char *sha1,
325 const char *base, int baselen,
326 const char *pathname, unsigned mode, int stage, void *context)
328 printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
329 return 0;
332 static void show_rev_tweak_rev(struct rev_info *rev, struct setup_revision_opt *opt)
334 if (rev->ignore_merges) {
335 /* There was no "-m" on the command line */
336 rev->ignore_merges = 0;
337 if (!rev->first_parent_only && !rev->combine_merges) {
338 /* No "--first-parent", "-c", nor "--cc" */
339 rev->combine_merges = 1;
340 rev->dense_combined_merges = 1;
343 if (!rev->diffopt.output_format)
344 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
347 int cmd_show(int argc, const char **argv, const char *prefix)
349 struct rev_info rev;
350 struct object_array_entry *objects;
351 struct setup_revision_opt opt;
352 int i, count, ret = 0;
354 git_config(git_log_config, NULL);
356 if (diff_use_color_default == -1)
357 diff_use_color_default = git_use_color_default;
359 init_revisions(&rev, prefix);
360 rev.diff = 1;
361 rev.always_show_header = 1;
362 rev.no_walk = 1;
363 memset(&opt, 0, sizeof(opt));
364 opt.def = "HEAD";
365 opt.tweak = show_rev_tweak_rev;
366 cmd_log_init(argc, argv, prefix, &rev, &opt);
368 count = rev.pending.nr;
369 objects = rev.pending.objects;
370 for (i = 0; i < count && !ret; i++) {
371 struct object *o = objects[i].item;
372 const char *name = objects[i].name;
373 switch (o->type) {
374 case OBJ_BLOB:
375 ret = show_object(o->sha1, 0, NULL);
376 break;
377 case OBJ_TAG: {
378 struct tag *t = (struct tag *)o;
380 if (rev.shown_one)
381 putchar('\n');
382 printf("%stag %s%s\n",
383 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
384 t->tag,
385 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
386 ret = show_object(o->sha1, 1, &rev);
387 rev.shown_one = 1;
388 if (ret)
389 break;
390 o = parse_object(t->tagged->sha1);
391 if (!o)
392 ret = error("Could not read object %s",
393 sha1_to_hex(t->tagged->sha1));
394 objects[i].item = o;
395 i--;
396 break;
398 case OBJ_TREE:
399 if (rev.shown_one)
400 putchar('\n');
401 printf("%stree %s%s\n\n",
402 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
403 name,
404 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
405 read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
406 show_tree_object, NULL);
407 rev.shown_one = 1;
408 break;
409 case OBJ_COMMIT:
410 rev.pending.nr = rev.pending.alloc = 0;
411 rev.pending.objects = NULL;
412 add_object_array(o, name, &rev.pending);
413 ret = cmd_log_walk(&rev);
414 break;
415 default:
416 ret = error("Unknown type: %d", o->type);
419 free(objects);
420 return ret;
424 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
426 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
428 struct rev_info rev;
429 struct setup_revision_opt opt;
431 git_config(git_log_config, NULL);
433 if (diff_use_color_default == -1)
434 diff_use_color_default = git_use_color_default;
436 init_revisions(&rev, prefix);
437 init_reflog_walk(&rev.reflog_info);
438 rev.abbrev_commit = 1;
439 rev.verbose_header = 1;
440 memset(&opt, 0, sizeof(opt));
441 opt.def = "HEAD";
442 cmd_log_init(argc, argv, prefix, &rev, &opt);
445 * This means that we override whatever commit format the user gave
446 * on the cmd line. Sad, but cmd_log_init() currently doesn't
447 * allow us to set a different default.
449 rev.commit_format = CMIT_FMT_ONELINE;
450 rev.use_terminator = 1;
451 rev.always_show_header = 1;
454 * We get called through "git reflog", so unlike the other log
455 * routines, we need to set up our pager manually..
457 setup_pager();
459 return cmd_log_walk(&rev);
462 int cmd_log(int argc, const char **argv, const char *prefix)
464 struct rev_info rev;
465 struct setup_revision_opt opt;
467 git_config(git_log_config, NULL);
469 if (diff_use_color_default == -1)
470 diff_use_color_default = git_use_color_default;
472 init_revisions(&rev, prefix);
473 rev.always_show_header = 1;
474 memset(&opt, 0, sizeof(opt));
475 opt.def = "HEAD";
476 cmd_log_init(argc, argv, prefix, &rev, &opt);
477 return cmd_log_walk(&rev);
480 /* format-patch */
482 static const char *fmt_patch_suffix = ".patch";
483 static int numbered = 0;
484 static int auto_number = 1;
486 static char *default_attach = NULL;
488 static struct string_list extra_hdr;
489 static struct string_list extra_to;
490 static struct string_list extra_cc;
492 static void add_header(const char *value)
494 struct string_list_item *item;
495 int len = strlen(value);
496 while (len && value[len - 1] == '\n')
497 len--;
499 if (!strncasecmp(value, "to: ", 4)) {
500 item = string_list_append(value + 4, &extra_to);
501 len -= 4;
502 } else if (!strncasecmp(value, "cc: ", 4)) {
503 item = string_list_append(value + 4, &extra_cc);
504 len -= 4;
505 } else {
506 item = string_list_append(value, &extra_hdr);
509 item->string[len] = '\0';
512 #define THREAD_SHALLOW 1
513 #define THREAD_DEEP 2
514 static int thread = 0;
515 static int do_signoff = 0;
517 static int git_format_config(const char *var, const char *value, void *cb)
519 if (!strcmp(var, "format.headers")) {
520 if (!value)
521 die("format.headers without value");
522 add_header(value);
523 return 0;
525 if (!strcmp(var, "format.suffix"))
526 return git_config_string(&fmt_patch_suffix, var, value);
527 if (!strcmp(var, "format.to")) {
528 if (!value)
529 return config_error_nonbool(var);
530 string_list_append(value, &extra_to);
531 return 0;
533 if (!strcmp(var, "format.cc")) {
534 if (!value)
535 return config_error_nonbool(var);
536 string_list_append(value, &extra_cc);
537 return 0;
539 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
540 return 0;
542 if (!strcmp(var, "format.numbered")) {
543 if (value && !strcasecmp(value, "auto")) {
544 auto_number = 1;
545 return 0;
547 numbered = git_config_bool(var, value);
548 auto_number = auto_number && numbered;
549 return 0;
551 if (!strcmp(var, "format.attach")) {
552 if (value && *value)
553 default_attach = xstrdup(value);
554 else
555 default_attach = xstrdup(git_version_string);
556 return 0;
558 if (!strcmp(var, "format.thread")) {
559 if (value && !strcasecmp(value, "deep")) {
560 thread = THREAD_DEEP;
561 return 0;
563 if (value && !strcasecmp(value, "shallow")) {
564 thread = THREAD_SHALLOW;
565 return 0;
567 thread = git_config_bool(var, value) && THREAD_SHALLOW;
568 return 0;
570 if (!strcmp(var, "format.signoff")) {
571 do_signoff = git_config_bool(var, value);
572 return 0;
575 return git_log_config(var, value, cb);
578 static FILE *realstdout = NULL;
579 static const char *output_directory = NULL;
580 static int outdir_offset;
582 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
584 struct strbuf filename = STRBUF_INIT;
585 int suffix_len = strlen(fmt_patch_suffix) + 1;
587 if (output_directory) {
588 strbuf_addstr(&filename, output_directory);
589 if (filename.len >=
590 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
591 return error("name of output directory is too long");
592 if (filename.buf[filename.len - 1] != '/')
593 strbuf_addch(&filename, '/');
596 get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
598 if (!DIFF_OPT_TST(&rev->diffopt, QUICK))
599 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
601 if (freopen(filename.buf, "w", stdout) == NULL)
602 return error("Cannot open patch file %s", filename.buf);
604 strbuf_release(&filename);
605 return 0;
608 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
610 struct rev_info check_rev;
611 struct commit *commit;
612 struct object *o1, *o2;
613 unsigned flags1, flags2;
615 if (rev->pending.nr != 2)
616 die("Need exactly one range.");
618 o1 = rev->pending.objects[0].item;
619 flags1 = o1->flags;
620 o2 = rev->pending.objects[1].item;
621 flags2 = o2->flags;
623 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
624 die("Not a range.");
626 init_patch_ids(ids);
628 /* given a range a..b get all patch ids for b..a */
629 init_revisions(&check_rev, prefix);
630 o1->flags ^= UNINTERESTING;
631 o2->flags ^= UNINTERESTING;
632 add_pending_object(&check_rev, o1, "o1");
633 add_pending_object(&check_rev, o2, "o2");
634 if (prepare_revision_walk(&check_rev))
635 die("revision walk setup failed");
637 while ((commit = get_revision(&check_rev)) != NULL) {
638 /* ignore merges */
639 if (commit->parents && commit->parents->next)
640 continue;
642 add_commit_patch_id(commit, ids);
645 /* reset for next revision walk */
646 clear_commit_marks((struct commit *)o1,
647 SEEN | UNINTERESTING | SHOWN | ADDED);
648 clear_commit_marks((struct commit *)o2,
649 SEEN | UNINTERESTING | SHOWN | ADDED);
650 o1->flags = flags1;
651 o2->flags = flags2;
654 static void gen_message_id(struct rev_info *info, char *base)
656 const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
657 const char *email_start = strrchr(committer, '<');
658 const char *email_end = strrchr(committer, '>');
659 struct strbuf buf = STRBUF_INIT;
660 if (!email_start || !email_end || email_start > email_end - 1)
661 die("Could not extract email from committer identity.");
662 strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
663 (unsigned long) time(NULL),
664 (int)(email_end - email_start - 1), email_start + 1);
665 info->message_id = strbuf_detach(&buf, NULL);
668 static void make_cover_letter(struct rev_info *rev, int use_stdout,
669 int numbered, int numbered_files,
670 struct commit *origin,
671 int nr, struct commit **list, struct commit *head)
673 const char *committer;
674 const char *subject_start = NULL;
675 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
676 const char *msg;
677 const char *extra_headers = rev->extra_headers;
678 struct shortlog log;
679 struct strbuf sb = STRBUF_INIT;
680 int i;
681 const char *encoding = "UTF-8";
682 struct diff_options opts;
683 int need_8bit_cte = 0;
684 struct commit *commit = NULL;
686 if (rev->commit_format != CMIT_FMT_EMAIL)
687 die("Cover letter needs email format");
689 committer = git_committer_info(0);
691 if (!numbered_files) {
693 * We fake a commit for the cover letter so we get the filename
694 * desired.
696 commit = xcalloc(1, sizeof(*commit));
697 commit->buffer = xmalloc(400);
698 snprintf(commit->buffer, 400,
699 "tree 0000000000000000000000000000000000000000\n"
700 "parent %s\n"
701 "author %s\n"
702 "committer %s\n\n"
703 "cover letter\n",
704 sha1_to_hex(head->object.sha1), committer, committer);
707 if (!use_stdout && reopen_stdout(commit, rev))
708 return;
710 if (commit) {
712 free(commit->buffer);
713 free(commit);
716 log_write_email_headers(rev, head, &subject_start, &extra_headers,
717 &need_8bit_cte);
719 for (i = 0; !need_8bit_cte && i < nr; i++)
720 if (has_non_ascii(list[i]->buffer))
721 need_8bit_cte = 1;
723 msg = body;
724 pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
725 encoding);
726 pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
727 encoding, need_8bit_cte);
728 pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
729 printf("%s\n", sb.buf);
731 strbuf_release(&sb);
733 shortlog_init(&log);
734 log.wrap_lines = 1;
735 log.wrap = 72;
736 log.in1 = 2;
737 log.in2 = 4;
738 for (i = 0; i < nr; i++)
739 shortlog_add_commit(&log, list[i]);
741 shortlog_output(&log);
744 * We can only do diffstat with a unique reference point
746 if (!origin)
747 return;
749 memcpy(&opts, &rev->diffopt, sizeof(opts));
750 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
752 diff_setup_done(&opts);
754 diff_tree_sha1(origin->tree->object.sha1,
755 head->tree->object.sha1,
756 "", &opts);
757 diffcore_std(&opts);
758 diff_flush(&opts);
760 printf("\n");
763 static const char *clean_message_id(const char *msg_id)
765 char ch;
766 const char *a, *z, *m;
768 m = msg_id;
769 while ((ch = *m) && (isspace(ch) || (ch == '<')))
770 m++;
771 a = m;
772 z = NULL;
773 while ((ch = *m)) {
774 if (!isspace(ch) && (ch != '>'))
775 z = m;
776 m++;
778 if (!z)
779 die("insane in-reply-to: %s", msg_id);
780 if (++z == m)
781 return a;
782 return xmemdupz(a, z - a);
785 static const char *set_outdir(const char *prefix, const char *output_directory)
787 if (output_directory && is_absolute_path(output_directory))
788 return output_directory;
790 if (!prefix || !*prefix) {
791 if (output_directory)
792 return output_directory;
793 /* The user did not explicitly ask for "./" */
794 outdir_offset = 2;
795 return "./";
798 outdir_offset = strlen(prefix);
799 if (!output_directory)
800 return prefix;
802 return xstrdup(prefix_filename(prefix, outdir_offset,
803 output_directory));
806 static const char * const builtin_format_patch_usage[] = {
807 "git format-patch [options] [<since> | <revision range>]",
808 NULL
811 static int keep_subject = 0;
813 static int keep_callback(const struct option *opt, const char *arg, int unset)
815 ((struct rev_info *)opt->value)->total = -1;
816 keep_subject = 1;
817 return 0;
820 static int subject_prefix = 0;
822 static int subject_prefix_callback(const struct option *opt, const char *arg,
823 int unset)
825 subject_prefix = 1;
826 ((struct rev_info *)opt->value)->subject_prefix = arg;
827 return 0;
830 static int numbered_cmdline_opt = 0;
832 static int numbered_callback(const struct option *opt, const char *arg,
833 int unset)
835 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
836 if (unset)
837 auto_number = 0;
838 return 0;
841 static int no_numbered_callback(const struct option *opt, const char *arg,
842 int unset)
844 return numbered_callback(opt, arg, 1);
847 static int output_directory_callback(const struct option *opt, const char *arg,
848 int unset)
850 const char **dir = (const char **)opt->value;
851 if (*dir)
852 die("Two output directories?");
853 *dir = arg;
854 return 0;
857 static int thread_callback(const struct option *opt, const char *arg, int unset)
859 int *thread = (int *)opt->value;
860 if (unset)
861 *thread = 0;
862 else if (!arg || !strcmp(arg, "shallow"))
863 *thread = THREAD_SHALLOW;
864 else if (!strcmp(arg, "deep"))
865 *thread = THREAD_DEEP;
866 else
867 return 1;
868 return 0;
871 static int attach_callback(const struct option *opt, const char *arg, int unset)
873 struct rev_info *rev = (struct rev_info *)opt->value;
874 if (unset)
875 rev->mime_boundary = NULL;
876 else if (arg)
877 rev->mime_boundary = arg;
878 else
879 rev->mime_boundary = git_version_string;
880 rev->no_inline = unset ? 0 : 1;
881 return 0;
884 static int inline_callback(const struct option *opt, const char *arg, int unset)
886 struct rev_info *rev = (struct rev_info *)opt->value;
887 if (unset)
888 rev->mime_boundary = NULL;
889 else if (arg)
890 rev->mime_boundary = arg;
891 else
892 rev->mime_boundary = git_version_string;
893 rev->no_inline = 0;
894 return 0;
897 static int header_callback(const struct option *opt, const char *arg, int unset)
899 if (unset) {
900 string_list_clear(&extra_hdr, 0);
901 string_list_clear(&extra_to, 0);
902 string_list_clear(&extra_cc, 0);
903 } else {
904 add_header(arg);
906 return 0;
909 static int to_callback(const struct option *opt, const char *arg, int unset)
911 if (unset)
912 string_list_clear(&extra_to, 0);
913 else
914 string_list_append(arg, &extra_to);
915 return 0;
918 static int cc_callback(const struct option *opt, const char *arg, int unset)
920 if (unset)
921 string_list_clear(&extra_cc, 0);
922 else
923 string_list_append(arg, &extra_cc);
924 return 0;
927 int cmd_format_patch(int argc, const char **argv, const char *prefix)
929 struct commit *commit;
930 struct commit **list = NULL;
931 struct rev_info rev;
932 struct setup_revision_opt s_r_opt;
933 int nr = 0, total, i;
934 int use_stdout = 0;
935 int start_number = -1;
936 int numbered_files = 0; /* _just_ numbers */
937 int ignore_if_in_upstream = 0;
938 int cover_letter = 0;
939 int boundary_count = 0;
940 int no_binary_diff = 0;
941 struct commit *origin = NULL, *head = NULL;
942 const char *in_reply_to = NULL;
943 struct patch_ids ids;
944 char *add_signoff = NULL;
945 struct strbuf buf = STRBUF_INIT;
946 int use_patch_format = 0;
947 const struct option builtin_format_patch_options[] = {
948 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
949 "use [PATCH n/m] even with a single patch",
950 PARSE_OPT_NOARG, numbered_callback },
951 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
952 "use [PATCH] even with multiple patches",
953 PARSE_OPT_NOARG, no_numbered_callback },
954 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
955 OPT_BOOLEAN(0, "stdout", &use_stdout,
956 "print patches to standard out"),
957 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
958 "generate a cover letter"),
959 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
960 "use simple number sequence for output file names"),
961 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
962 "use <sfx> instead of '.patch'"),
963 OPT_INTEGER(0, "start-number", &start_number,
964 "start numbering patches at <n> instead of 1"),
965 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
966 "Use [<prefix>] instead of [PATCH]",
967 PARSE_OPT_NONEG, subject_prefix_callback },
968 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
969 "dir", "store resulting files in <dir>",
970 PARSE_OPT_NONEG, output_directory_callback },
971 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
972 "don't strip/add [PATCH]",
973 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
974 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
975 "don't output binary diffs"),
976 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
977 "don't include a patch matching a commit upstream"),
978 { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
979 "show patch format instead of default (patch + stat)",
980 PARSE_OPT_NONEG | PARSE_OPT_NOARG },
981 OPT_GROUP("Messaging"),
982 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
983 "add email header", 0, header_callback },
984 { OPTION_CALLBACK, 0, "to", NULL, "email", "add To: header",
985 0, to_callback },
986 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
987 0, cc_callback },
988 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
989 "make first mail a reply to <message-id>"),
990 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
991 "attach the patch", PARSE_OPT_OPTARG,
992 attach_callback },
993 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
994 "inline the patch",
995 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
996 inline_callback },
997 { OPTION_CALLBACK, 0, "thread", &thread, "style",
998 "enable message threading, styles: shallow, deep",
999 PARSE_OPT_OPTARG, thread_callback },
1000 OPT_END()
1003 extra_hdr.strdup_strings = 1;
1004 extra_to.strdup_strings = 1;
1005 extra_cc.strdup_strings = 1;
1006 git_config(git_format_config, NULL);
1007 init_revisions(&rev, prefix);
1008 rev.commit_format = CMIT_FMT_EMAIL;
1009 rev.verbose_header = 1;
1010 rev.diff = 1;
1011 rev.combine_merges = 0;
1012 rev.ignore_merges = 1;
1013 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1014 rev.subject_prefix = fmt_patch_subject_prefix;
1015 memset(&s_r_opt, 0, sizeof(s_r_opt));
1016 s_r_opt.def = "HEAD";
1018 if (default_attach) {
1019 rev.mime_boundary = default_attach;
1020 rev.no_inline = 1;
1024 * Parse the arguments before setup_revisions(), or something
1025 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1026 * possibly a valid SHA1.
1028 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1029 builtin_format_patch_usage,
1030 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1031 PARSE_OPT_KEEP_DASHDASH);
1033 if (do_signoff) {
1034 const char *committer;
1035 const char *endpos;
1036 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
1037 endpos = strchr(committer, '>');
1038 if (!endpos)
1039 die("bogus committer info %s", committer);
1040 add_signoff = xmemdupz(committer, endpos - committer + 1);
1043 for (i = 0; i < extra_hdr.nr; i++) {
1044 strbuf_addstr(&buf, extra_hdr.items[i].string);
1045 strbuf_addch(&buf, '\n');
1048 if (extra_to.nr)
1049 strbuf_addstr(&buf, "To: ");
1050 for (i = 0; i < extra_to.nr; i++) {
1051 if (i)
1052 strbuf_addstr(&buf, " ");
1053 strbuf_addstr(&buf, extra_to.items[i].string);
1054 if (i + 1 < extra_to.nr)
1055 strbuf_addch(&buf, ',');
1056 strbuf_addch(&buf, '\n');
1059 if (extra_cc.nr)
1060 strbuf_addstr(&buf, "Cc: ");
1061 for (i = 0; i < extra_cc.nr; i++) {
1062 if (i)
1063 strbuf_addstr(&buf, " ");
1064 strbuf_addstr(&buf, extra_cc.items[i].string);
1065 if (i + 1 < extra_cc.nr)
1066 strbuf_addch(&buf, ',');
1067 strbuf_addch(&buf, '\n');
1070 rev.extra_headers = strbuf_detach(&buf, NULL);
1072 if (start_number < 0)
1073 start_number = 1;
1076 * If numbered is set solely due to format.numbered in config,
1077 * and it would conflict with --keep-subject (-k) from the
1078 * command line, reset "numbered".
1080 if (numbered && keep_subject && !numbered_cmdline_opt)
1081 numbered = 0;
1083 if (numbered && keep_subject)
1084 die ("-n and -k are mutually exclusive.");
1085 if (keep_subject && subject_prefix)
1086 die ("--subject-prefix and -k are mutually exclusive.");
1088 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1089 if (argc > 1)
1090 die ("unrecognized argument: %s", argv[1]);
1092 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1093 die("--name-only does not make sense");
1094 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1095 die("--name-status does not make sense");
1096 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1097 die("--check does not make sense");
1099 if (!use_patch_format &&
1100 (!rev.diffopt.output_format ||
1101 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1102 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1104 /* Always generate a patch */
1105 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1107 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1108 DIFF_OPT_SET(&rev.diffopt, BINARY);
1110 if (rev.show_notes)
1111 init_display_notes(&rev.notes_opt);
1113 if (!use_stdout)
1114 output_directory = set_outdir(prefix, output_directory);
1116 if (output_directory) {
1117 if (use_stdout)
1118 die("standard output, or directory, which one?");
1119 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1120 die_errno("Could not create directory '%s'",
1121 output_directory);
1124 if (rev.pending.nr == 1) {
1125 if (rev.max_count < 0 && !rev.show_root_diff) {
1127 * This is traditional behaviour of "git format-patch
1128 * origin" that prepares what the origin side still
1129 * does not have.
1131 rev.pending.objects[0].item->flags |= UNINTERESTING;
1132 add_head_to_pending(&rev);
1135 * Otherwise, it is "format-patch -22 HEAD", and/or
1136 * "format-patch --root HEAD". The user wants
1137 * get_revision() to do the usual traversal.
1142 * We cannot move this anywhere earlier because we do want to
1143 * know if --root was given explicitly from the command line.
1145 rev.show_root_diff = 1;
1147 if (cover_letter) {
1148 /* remember the range */
1149 int i;
1150 for (i = 0; i < rev.pending.nr; i++) {
1151 struct object *o = rev.pending.objects[i].item;
1152 if (!(o->flags & UNINTERESTING))
1153 head = (struct commit *)o;
1155 /* We can't generate a cover letter without any patches */
1156 if (!head)
1157 return 0;
1160 if (ignore_if_in_upstream)
1161 get_patch_ids(&rev, &ids, prefix);
1163 if (!use_stdout)
1164 realstdout = xfdopen(xdup(1), "w");
1166 if (prepare_revision_walk(&rev))
1167 die("revision walk setup failed");
1168 rev.boundary = 1;
1169 while ((commit = get_revision(&rev)) != NULL) {
1170 if (commit->object.flags & BOUNDARY) {
1171 boundary_count++;
1172 origin = (boundary_count == 1) ? commit : NULL;
1173 continue;
1176 /* ignore merges */
1177 if (commit->parents && commit->parents->next)
1178 continue;
1180 if (ignore_if_in_upstream &&
1181 has_commit_patch_id(commit, &ids))
1182 continue;
1184 nr++;
1185 list = xrealloc(list, nr * sizeof(list[0]));
1186 list[nr - 1] = commit;
1188 total = nr;
1189 if (!keep_subject && auto_number && total > 1)
1190 numbered = 1;
1191 if (numbered)
1192 rev.total = total + start_number - 1;
1193 if (in_reply_to || thread || cover_letter)
1194 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1195 if (in_reply_to) {
1196 const char *msgid = clean_message_id(in_reply_to);
1197 string_list_append(msgid, rev.ref_message_ids);
1199 rev.numbered_files = numbered_files;
1200 rev.patch_suffix = fmt_patch_suffix;
1201 if (cover_letter) {
1202 if (thread)
1203 gen_message_id(&rev, "cover");
1204 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1205 origin, nr, list, head);
1206 total++;
1207 start_number--;
1209 rev.add_signoff = add_signoff;
1210 while (0 <= --nr) {
1211 int shown;
1212 commit = list[nr];
1213 rev.nr = total - nr + (start_number - 1);
1214 /* Make the second and subsequent mails replies to the first */
1215 if (thread) {
1216 /* Have we already had a message ID? */
1217 if (rev.message_id) {
1219 * For deep threading: make every mail
1220 * a reply to the previous one, no
1221 * matter what other options are set.
1223 * For shallow threading:
1225 * Without --cover-letter and
1226 * --in-reply-to, make every mail a
1227 * reply to the one before.
1229 * With --in-reply-to but no
1230 * --cover-letter, make every mail a
1231 * reply to the <reply-to>.
1233 * With --cover-letter, make every
1234 * mail but the cover letter a reply
1235 * to the cover letter. The cover
1236 * letter is a reply to the
1237 * --in-reply-to, if specified.
1239 if (thread == THREAD_SHALLOW
1240 && rev.ref_message_ids->nr > 0
1241 && (!cover_letter || rev.nr > 1))
1242 free(rev.message_id);
1243 else
1244 string_list_append(rev.message_id,
1245 rev.ref_message_ids);
1247 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1250 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1251 &rev))
1252 die("Failed to create output files");
1253 shown = log_tree_commit(&rev, commit);
1254 free(commit->buffer);
1255 commit->buffer = NULL;
1257 /* We put one extra blank line between formatted
1258 * patches and this flag is used by log-tree code
1259 * to see if it needs to emit a LF before showing
1260 * the log; when using one file per patch, we do
1261 * not want the extra blank line.
1263 if (!use_stdout)
1264 rev.shown_one = 0;
1265 if (shown) {
1266 if (rev.mime_boundary)
1267 printf("\n--%s%s--\n\n\n",
1268 mime_boundary_leader,
1269 rev.mime_boundary);
1270 else
1271 printf("-- \n%s\n\n", git_version_string);
1273 if (!use_stdout)
1274 fclose(stdout);
1276 free(list);
1277 string_list_clear(&extra_to, 0);
1278 string_list_clear(&extra_cc, 0);
1279 string_list_clear(&extra_hdr, 0);
1280 if (ignore_if_in_upstream)
1281 free_patch_ids(&ids);
1282 return 0;
1285 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1287 unsigned char sha1[20];
1288 if (get_sha1(arg, sha1) == 0) {
1289 struct commit *commit = lookup_commit_reference(sha1);
1290 if (commit) {
1291 commit->object.flags |= flags;
1292 add_pending_object(revs, &commit->object, arg);
1293 return 0;
1296 return -1;
1299 static const char cherry_usage[] =
1300 "git cherry [-v] [<upstream> [<head> [<limit>]]]";
1301 int cmd_cherry(int argc, const char **argv, const char *prefix)
1303 struct rev_info revs;
1304 struct patch_ids ids;
1305 struct commit *commit;
1306 struct commit_list *list = NULL;
1307 struct branch *current_branch;
1308 const char *upstream;
1309 const char *head = "HEAD";
1310 const char *limit = NULL;
1311 int verbose = 0;
1313 if (argc > 1 && !strcmp(argv[1], "-v")) {
1314 verbose = 1;
1315 argc--;
1316 argv++;
1319 if (argc > 1 && !strcmp(argv[1], "-h"))
1320 usage(cherry_usage);
1322 switch (argc) {
1323 case 4:
1324 limit = argv[3];
1325 /* FALLTHROUGH */
1326 case 3:
1327 head = argv[2];
1328 /* FALLTHROUGH */
1329 case 2:
1330 upstream = argv[1];
1331 break;
1332 default:
1333 current_branch = branch_get(NULL);
1334 if (!current_branch || !current_branch->merge
1335 || !current_branch->merge[0]
1336 || !current_branch->merge[0]->dst) {
1337 fprintf(stderr, "Could not find a tracked"
1338 " remote branch, please"
1339 " specify <upstream> manually.\n");
1340 usage(cherry_usage);
1343 upstream = current_branch->merge[0]->dst;
1346 init_revisions(&revs, prefix);
1347 revs.diff = 1;
1348 revs.combine_merges = 0;
1349 revs.ignore_merges = 1;
1350 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1352 if (add_pending_commit(head, &revs, 0))
1353 die("Unknown commit %s", head);
1354 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1355 die("Unknown commit %s", upstream);
1357 /* Don't say anything if head and upstream are the same. */
1358 if (revs.pending.nr == 2) {
1359 struct object_array_entry *o = revs.pending.objects;
1360 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1361 return 0;
1364 get_patch_ids(&revs, &ids, prefix);
1366 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1367 die("Unknown commit %s", limit);
1369 /* reverse the list of commits */
1370 if (prepare_revision_walk(&revs))
1371 die("revision walk setup failed");
1372 while ((commit = get_revision(&revs)) != NULL) {
1373 /* ignore merges */
1374 if (commit->parents && commit->parents->next)
1375 continue;
1377 commit_list_insert(commit, &list);
1380 while (list) {
1381 char sign = '+';
1383 commit = list->item;
1384 if (has_commit_patch_id(commit, &ids))
1385 sign = '-';
1387 if (verbose) {
1388 struct strbuf buf = STRBUF_INIT;
1389 struct pretty_print_context ctx = {0};
1390 pretty_print_commit(CMIT_FMT_ONELINE, commit,
1391 &buf, &ctx);
1392 printf("%c %s %s\n", sign,
1393 sha1_to_hex(commit->object.sha1), buf.buf);
1394 strbuf_release(&buf);
1396 else {
1397 printf("%c %s\n", sign,
1398 sha1_to_hex(commit->object.sha1));
1401 list = list->next;
1404 free_patch_ids(&ids);
1405 return 0;