Merge branch 'ic/bash-completion-rpm' into next
[git/wpalmer.git] / builtin / log.c
blob362dd427600e32c4ea572a19d5e1bd0c97867d55
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 int decoration_style;
28 static const char *fmt_patch_subject_prefix = "PATCH";
29 static const char *fmt_pretty;
31 static const char * const builtin_log_usage =
32 "git log [<options>] [<since>..<until>] [[--] <path>...]\n"
33 " or: git show [options] <object>...";
35 static int parse_decoration_style(const char *var, const char *value)
37 switch (git_config_maybe_bool(var, value)) {
38 case 1:
39 return DECORATE_SHORT_REFS;
40 case 0:
41 return 0;
42 default:
43 break;
45 if (!strcmp(value, "full"))
46 return DECORATE_FULL_REFS;
47 else if (!strcmp(value, "short"))
48 return DECORATE_SHORT_REFS;
49 return -1;
52 static void cmd_log_init(int argc, const char **argv, const char *prefix,
53 struct rev_info *rev, struct setup_revision_opt *opt)
55 int i;
57 rev->abbrev = DEFAULT_ABBREV;
58 rev->commit_format = CMIT_FMT_DEFAULT;
59 if (fmt_pretty)
60 get_commit_format(fmt_pretty, rev);
61 rev->verbose_header = 1;
62 DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
63 rev->show_root_diff = default_show_root;
64 rev->subject_prefix = fmt_patch_subject_prefix;
65 DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
67 if (default_date_mode)
68 rev->date_mode = parse_date_format(default_date_mode);
71 * Check for -h before setup_revisions(), or "git log -h" will
72 * fail when run without a git directory.
74 if (argc == 2 && !strcmp(argv[1], "-h"))
75 usage(builtin_log_usage);
76 argc = setup_revisions(argc, argv, rev, opt);
78 if (!rev->show_notes_given && !rev->pretty_given)
79 rev->show_notes = 1;
80 if (rev->show_notes)
81 init_display_notes(&rev->notes_opt);
83 if (rev->diffopt.pickaxe || rev->diffopt.filter)
84 rev->always_show_header = 0;
85 if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
86 rev->always_show_header = 0;
87 if (rev->diffopt.nr_paths != 1)
88 usage("git logs can only follow renames on one pathname at a time");
90 for (i = 1; i < argc; i++) {
91 const char *arg = argv[i];
92 if (!strcmp(arg, "--decorate")) {
93 decoration_style = DECORATE_SHORT_REFS;
94 } else if (!prefixcmp(arg, "--decorate=")) {
95 const char *v = skip_prefix(arg, "--decorate=");
96 decoration_style = parse_decoration_style(arg, v);
97 if (decoration_style < 0)
98 die("invalid --decorate option: %s", arg);
99 } else if (!strcmp(arg, "--no-decorate")) {
100 decoration_style = 0;
101 } else if (!strcmp(arg, "--source")) {
102 rev->show_source = 1;
103 } else if (!strcmp(arg, "-h")) {
104 usage(builtin_log_usage);
105 } else
106 die("unrecognized argument: %s", arg);
108 if (decoration_style) {
109 rev->show_decorations = 1;
110 load_ref_decorations(decoration_style);
115 * This gives a rough estimate for how many commits we
116 * will print out in the list.
118 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
120 int n = 0;
122 while (list) {
123 struct commit *commit = list->item;
124 unsigned int flags = commit->object.flags;
125 list = list->next;
126 if (!(flags & (TREESAME | UNINTERESTING)))
127 n++;
129 return n;
132 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
134 if (rev->shown_one) {
135 rev->shown_one = 0;
136 if (rev->commit_format != CMIT_FMT_ONELINE)
137 putchar(rev->diffopt.line_termination);
139 printf("Final output: %d %s\n", nr, stage);
142 static struct itimerval early_output_timer;
144 static void log_show_early(struct rev_info *revs, struct commit_list *list)
146 int i = revs->early_output;
147 int show_header = 1;
149 sort_in_topological_order(&list, revs->lifo);
150 while (list && i) {
151 struct commit *commit = list->item;
152 switch (simplify_commit(revs, commit)) {
153 case commit_show:
154 if (show_header) {
155 int n = estimate_commit_count(revs, list);
156 show_early_header(revs, "incomplete", n);
157 show_header = 0;
159 log_tree_commit(revs, commit);
160 i--;
161 break;
162 case commit_ignore:
163 break;
164 case commit_error:
165 return;
167 list = list->next;
170 /* Did we already get enough commits for the early output? */
171 if (!i)
172 return;
175 * ..if no, then repeat it twice a second until we
176 * do.
178 * NOTE! We don't use "it_interval", because if the
179 * reader isn't listening, we want our output to be
180 * throttled by the writing, and not have the timer
181 * trigger every second even if we're blocked on a
182 * reader!
184 early_output_timer.it_value.tv_sec = 0;
185 early_output_timer.it_value.tv_usec = 500000;
186 setitimer(ITIMER_REAL, &early_output_timer, NULL);
189 static void early_output(int signal)
191 show_early_output = log_show_early;
194 static void setup_early_output(struct rev_info *rev)
196 struct sigaction sa;
199 * Set up the signal handler, minimally intrusively:
200 * we only set a single volatile integer word (not
201 * using sigatomic_t - trying to avoid unnecessary
202 * system dependencies and headers), and using
203 * SA_RESTART.
205 memset(&sa, 0, sizeof(sa));
206 sa.sa_handler = early_output;
207 sigemptyset(&sa.sa_mask);
208 sa.sa_flags = SA_RESTART;
209 sigaction(SIGALRM, &sa, NULL);
212 * If we can get the whole output in less than a
213 * tenth of a second, don't even bother doing the
214 * early-output thing..
216 * This is a one-time-only trigger.
218 early_output_timer.it_value.tv_sec = 0;
219 early_output_timer.it_value.tv_usec = 100000;
220 setitimer(ITIMER_REAL, &early_output_timer, NULL);
223 static void finish_early_output(struct rev_info *rev)
225 int n = estimate_commit_count(rev, rev->commits);
226 signal(SIGALRM, SIG_IGN);
227 show_early_header(rev, "done", n);
230 static int cmd_log_walk(struct rev_info *rev)
232 struct commit *commit;
234 if (rev->early_output)
235 setup_early_output(rev);
237 if (prepare_revision_walk(rev))
238 die("revision walk setup failed");
240 if (rev->early_output)
241 finish_early_output(rev);
244 * For --check and --exit-code, the exit code is based on CHECK_FAILED
245 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
246 * retain that state information if replacing rev->diffopt in this loop
248 while ((commit = get_revision(rev)) != NULL) {
249 log_tree_commit(rev, commit);
250 if (!rev->reflog_info) {
251 /* we allow cycles in reflog ancestry */
252 free(commit->buffer);
253 commit->buffer = NULL;
255 free_commit_list(commit->parents);
256 commit->parents = NULL;
258 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
259 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
260 return 02;
262 return diff_result_code(&rev->diffopt, 0);
265 static int git_log_config(const char *var, const char *value, void *cb)
267 if (!strcmp(var, "format.pretty"))
268 return git_config_string(&fmt_pretty, var, value);
269 if (!strcmp(var, "format.subjectprefix"))
270 return git_config_string(&fmt_patch_subject_prefix, var, value);
271 if (!strcmp(var, "log.date"))
272 return git_config_string(&default_date_mode, var, value);
273 if (!strcmp(var, "log.decorate")) {
274 decoration_style = parse_decoration_style(var, value);
275 if (decoration_style < 0)
276 decoration_style = 0; /* maybe warn? */
277 return 0;
279 if (!strcmp(var, "log.showroot")) {
280 default_show_root = git_config_bool(var, value);
281 return 0;
283 return git_diff_ui_config(var, value, cb);
286 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
288 struct rev_info rev;
289 struct setup_revision_opt opt;
291 git_config(git_log_config, NULL);
293 if (diff_use_color_default == -1)
294 diff_use_color_default = git_use_color_default;
296 init_revisions(&rev, prefix);
297 rev.diff = 1;
298 rev.simplify_history = 0;
299 memset(&opt, 0, sizeof(opt));
300 opt.def = "HEAD";
301 cmd_log_init(argc, argv, prefix, &rev, &opt);
302 if (!rev.diffopt.output_format)
303 rev.diffopt.output_format = DIFF_FORMAT_RAW;
304 return cmd_log_walk(&rev);
307 static void show_tagger(char *buf, int len, struct rev_info *rev)
309 struct strbuf out = STRBUF_INIT;
311 pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
312 git_log_output_encoding ?
313 git_log_output_encoding: git_commit_encoding);
314 printf("%s", out.buf);
315 strbuf_release(&out);
318 static int show_object(const unsigned char *sha1, int show_tag_object,
319 struct rev_info *rev)
321 unsigned long size;
322 enum object_type type;
323 char *buf = read_sha1_file(sha1, &type, &size);
324 int offset = 0;
326 if (!buf)
327 return error("Could not read object %s", sha1_to_hex(sha1));
329 if (show_tag_object)
330 while (offset < size && buf[offset] != '\n') {
331 int new_offset = offset + 1;
332 while (new_offset < size && buf[new_offset++] != '\n')
333 ; /* do nothing */
334 if (!prefixcmp(buf + offset, "tagger "))
335 show_tagger(buf + offset + 7,
336 new_offset - offset - 7, rev);
337 offset = new_offset;
340 if (offset < size)
341 fwrite(buf + offset, size - offset, 1, stdout);
342 free(buf);
343 return 0;
346 static int show_tree_object(const unsigned char *sha1,
347 const char *base, int baselen,
348 const char *pathname, unsigned mode, int stage, void *context)
350 printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
351 return 0;
354 static void show_rev_tweak_rev(struct rev_info *rev, struct setup_revision_opt *opt)
356 if (rev->ignore_merges) {
357 /* There was no "-m" on the command line */
358 rev->ignore_merges = 0;
359 if (!rev->first_parent_only && !rev->combine_merges) {
360 /* No "--first-parent", "-c", nor "--cc" */
361 rev->combine_merges = 1;
362 rev->dense_combined_merges = 1;
365 if (!rev->diffopt.output_format)
366 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
369 int cmd_show(int argc, const char **argv, const char *prefix)
371 struct rev_info rev;
372 struct object_array_entry *objects;
373 struct setup_revision_opt opt;
374 int i, count, ret = 0;
376 git_config(git_log_config, NULL);
378 if (diff_use_color_default == -1)
379 diff_use_color_default = git_use_color_default;
381 init_revisions(&rev, prefix);
382 rev.diff = 1;
383 rev.always_show_header = 1;
384 rev.no_walk = 1;
385 memset(&opt, 0, sizeof(opt));
386 opt.def = "HEAD";
387 opt.tweak = show_rev_tweak_rev;
388 cmd_log_init(argc, argv, prefix, &rev, &opt);
390 count = rev.pending.nr;
391 objects = rev.pending.objects;
392 for (i = 0; i < count && !ret; i++) {
393 struct object *o = objects[i].item;
394 const char *name = objects[i].name;
395 switch (o->type) {
396 case OBJ_BLOB:
397 ret = show_object(o->sha1, 0, NULL);
398 break;
399 case OBJ_TAG: {
400 struct tag *t = (struct tag *)o;
402 if (rev.shown_one)
403 putchar('\n');
404 printf("%stag %s%s\n",
405 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
406 t->tag,
407 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
408 ret = show_object(o->sha1, 1, &rev);
409 rev.shown_one = 1;
410 if (ret)
411 break;
412 o = parse_object(t->tagged->sha1);
413 if (!o)
414 ret = error("Could not read object %s",
415 sha1_to_hex(t->tagged->sha1));
416 objects[i].item = o;
417 i--;
418 break;
420 case OBJ_TREE:
421 if (rev.shown_one)
422 putchar('\n');
423 printf("%stree %s%s\n\n",
424 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
425 name,
426 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
427 read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
428 show_tree_object, NULL);
429 rev.shown_one = 1;
430 break;
431 case OBJ_COMMIT:
432 rev.pending.nr = rev.pending.alloc = 0;
433 rev.pending.objects = NULL;
434 add_object_array(o, name, &rev.pending);
435 ret = cmd_log_walk(&rev);
436 break;
437 default:
438 ret = error("Unknown type: %d", o->type);
441 free(objects);
442 return ret;
446 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
448 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
450 struct rev_info rev;
451 struct setup_revision_opt opt;
453 git_config(git_log_config, NULL);
455 if (diff_use_color_default == -1)
456 diff_use_color_default = git_use_color_default;
458 init_revisions(&rev, prefix);
459 init_reflog_walk(&rev.reflog_info);
460 rev.abbrev_commit = 1;
461 rev.verbose_header = 1;
462 memset(&opt, 0, sizeof(opt));
463 opt.def = "HEAD";
464 cmd_log_init(argc, argv, prefix, &rev, &opt);
467 * This means that we override whatever commit format the user gave
468 * on the cmd line. Sad, but cmd_log_init() currently doesn't
469 * allow us to set a different default.
471 rev.commit_format = CMIT_FMT_ONELINE;
472 rev.use_terminator = 1;
473 rev.always_show_header = 1;
476 * We get called through "git reflog", so unlike the other log
477 * routines, we need to set up our pager manually..
479 setup_pager();
481 return cmd_log_walk(&rev);
484 int cmd_log(int argc, const char **argv, const char *prefix)
486 struct rev_info rev;
487 struct setup_revision_opt opt;
489 git_config(git_log_config, NULL);
491 if (diff_use_color_default == -1)
492 diff_use_color_default = git_use_color_default;
494 init_revisions(&rev, prefix);
495 rev.always_show_header = 1;
496 memset(&opt, 0, sizeof(opt));
497 opt.def = "HEAD";
498 cmd_log_init(argc, argv, prefix, &rev, &opt);
499 return cmd_log_walk(&rev);
502 /* format-patch */
504 static const char *fmt_patch_suffix = ".patch";
505 static int numbered = 0;
506 static int auto_number = 1;
508 static char *default_attach = NULL;
510 static struct string_list extra_hdr;
511 static struct string_list extra_to;
512 static struct string_list extra_cc;
514 static void add_header(const char *value)
516 struct string_list_item *item;
517 int len = strlen(value);
518 while (len && value[len - 1] == '\n')
519 len--;
521 if (!strncasecmp(value, "to: ", 4)) {
522 item = string_list_append(value + 4, &extra_to);
523 len -= 4;
524 } else if (!strncasecmp(value, "cc: ", 4)) {
525 item = string_list_append(value + 4, &extra_cc);
526 len -= 4;
527 } else {
528 item = string_list_append(value, &extra_hdr);
531 item->string[len] = '\0';
534 #define THREAD_SHALLOW 1
535 #define THREAD_DEEP 2
536 static int thread = 0;
537 static int do_signoff = 0;
539 static int git_format_config(const char *var, const char *value, void *cb)
541 if (!strcmp(var, "format.headers")) {
542 if (!value)
543 die("format.headers without value");
544 add_header(value);
545 return 0;
547 if (!strcmp(var, "format.suffix"))
548 return git_config_string(&fmt_patch_suffix, var, value);
549 if (!strcmp(var, "format.to")) {
550 if (!value)
551 return config_error_nonbool(var);
552 string_list_append(value, &extra_to);
553 return 0;
555 if (!strcmp(var, "format.cc")) {
556 if (!value)
557 return config_error_nonbool(var);
558 string_list_append(value, &extra_cc);
559 return 0;
561 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
562 return 0;
564 if (!strcmp(var, "format.numbered")) {
565 if (value && !strcasecmp(value, "auto")) {
566 auto_number = 1;
567 return 0;
569 numbered = git_config_bool(var, value);
570 auto_number = auto_number && numbered;
571 return 0;
573 if (!strcmp(var, "format.attach")) {
574 if (value && *value)
575 default_attach = xstrdup(value);
576 else
577 default_attach = xstrdup(git_version_string);
578 return 0;
580 if (!strcmp(var, "format.thread")) {
581 if (value && !strcasecmp(value, "deep")) {
582 thread = THREAD_DEEP;
583 return 0;
585 if (value && !strcasecmp(value, "shallow")) {
586 thread = THREAD_SHALLOW;
587 return 0;
589 thread = git_config_bool(var, value) && THREAD_SHALLOW;
590 return 0;
592 if (!strcmp(var, "format.signoff")) {
593 do_signoff = git_config_bool(var, value);
594 return 0;
597 return git_log_config(var, value, cb);
600 static FILE *realstdout = NULL;
601 static const char *output_directory = NULL;
602 static int outdir_offset;
604 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
606 struct strbuf filename = STRBUF_INIT;
607 int suffix_len = strlen(fmt_patch_suffix) + 1;
609 if (output_directory) {
610 strbuf_addstr(&filename, output_directory);
611 if (filename.len >=
612 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
613 return error("name of output directory is too long");
614 if (filename.buf[filename.len - 1] != '/')
615 strbuf_addch(&filename, '/');
618 get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
620 if (!DIFF_OPT_TST(&rev->diffopt, QUICK))
621 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
623 if (freopen(filename.buf, "w", stdout) == NULL)
624 return error("Cannot open patch file %s", filename.buf);
626 strbuf_release(&filename);
627 return 0;
630 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
632 struct rev_info check_rev;
633 struct commit *commit;
634 struct object *o1, *o2;
635 unsigned flags1, flags2;
637 if (rev->pending.nr != 2)
638 die("Need exactly one range.");
640 o1 = rev->pending.objects[0].item;
641 flags1 = o1->flags;
642 o2 = rev->pending.objects[1].item;
643 flags2 = o2->flags;
645 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
646 die("Not a range.");
648 init_patch_ids(ids);
650 /* given a range a..b get all patch ids for b..a */
651 init_revisions(&check_rev, prefix);
652 o1->flags ^= UNINTERESTING;
653 o2->flags ^= UNINTERESTING;
654 add_pending_object(&check_rev, o1, "o1");
655 add_pending_object(&check_rev, o2, "o2");
656 if (prepare_revision_walk(&check_rev))
657 die("revision walk setup failed");
659 while ((commit = get_revision(&check_rev)) != NULL) {
660 /* ignore merges */
661 if (commit->parents && commit->parents->next)
662 continue;
664 add_commit_patch_id(commit, ids);
667 /* reset for next revision walk */
668 clear_commit_marks((struct commit *)o1,
669 SEEN | UNINTERESTING | SHOWN | ADDED);
670 clear_commit_marks((struct commit *)o2,
671 SEEN | UNINTERESTING | SHOWN | ADDED);
672 o1->flags = flags1;
673 o2->flags = flags2;
676 static void gen_message_id(struct rev_info *info, char *base)
678 const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
679 const char *email_start = strrchr(committer, '<');
680 const char *email_end = strrchr(committer, '>');
681 struct strbuf buf = STRBUF_INIT;
682 if (!email_start || !email_end || email_start > email_end - 1)
683 die("Could not extract email from committer identity.");
684 strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
685 (unsigned long) time(NULL),
686 (int)(email_end - email_start - 1), email_start + 1);
687 info->message_id = strbuf_detach(&buf, NULL);
690 static void make_cover_letter(struct rev_info *rev, int use_stdout,
691 int numbered, int numbered_files,
692 struct commit *origin,
693 int nr, struct commit **list, struct commit *head)
695 const char *committer;
696 const char *subject_start = NULL;
697 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
698 const char *msg;
699 const char *extra_headers = rev->extra_headers;
700 struct shortlog log;
701 struct strbuf sb = STRBUF_INIT;
702 int i;
703 const char *encoding = "UTF-8";
704 struct diff_options opts;
705 int need_8bit_cte = 0;
706 struct commit *commit = NULL;
708 if (rev->commit_format != CMIT_FMT_EMAIL)
709 die("Cover letter needs email format");
711 committer = git_committer_info(0);
713 if (!numbered_files) {
715 * We fake a commit for the cover letter so we get the filename
716 * desired.
718 commit = xcalloc(1, sizeof(*commit));
719 commit->buffer = xmalloc(400);
720 snprintf(commit->buffer, 400,
721 "tree 0000000000000000000000000000000000000000\n"
722 "parent %s\n"
723 "author %s\n"
724 "committer %s\n\n"
725 "cover letter\n",
726 sha1_to_hex(head->object.sha1), committer, committer);
729 if (!use_stdout && reopen_stdout(commit, rev))
730 return;
732 if (commit) {
734 free(commit->buffer);
735 free(commit);
738 log_write_email_headers(rev, head, &subject_start, &extra_headers,
739 &need_8bit_cte);
741 for (i = 0; !need_8bit_cte && i < nr; i++)
742 if (has_non_ascii(list[i]->buffer))
743 need_8bit_cte = 1;
745 msg = body;
746 pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
747 encoding);
748 pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
749 encoding, need_8bit_cte);
750 pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
751 printf("%s\n", sb.buf);
753 strbuf_release(&sb);
755 shortlog_init(&log);
756 log.wrap_lines = 1;
757 log.wrap = 72;
758 log.in1 = 2;
759 log.in2 = 4;
760 for (i = 0; i < nr; i++)
761 shortlog_add_commit(&log, list[i]);
763 shortlog_output(&log);
766 * We can only do diffstat with a unique reference point
768 if (!origin)
769 return;
771 memcpy(&opts, &rev->diffopt, sizeof(opts));
772 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
774 diff_setup_done(&opts);
776 diff_tree_sha1(origin->tree->object.sha1,
777 head->tree->object.sha1,
778 "", &opts);
779 diffcore_std(&opts);
780 diff_flush(&opts);
782 printf("\n");
785 static const char *clean_message_id(const char *msg_id)
787 char ch;
788 const char *a, *z, *m;
790 m = msg_id;
791 while ((ch = *m) && (isspace(ch) || (ch == '<')))
792 m++;
793 a = m;
794 z = NULL;
795 while ((ch = *m)) {
796 if (!isspace(ch) && (ch != '>'))
797 z = m;
798 m++;
800 if (!z)
801 die("insane in-reply-to: %s", msg_id);
802 if (++z == m)
803 return a;
804 return xmemdupz(a, z - a);
807 static const char *set_outdir(const char *prefix, const char *output_directory)
809 if (output_directory && is_absolute_path(output_directory))
810 return output_directory;
812 if (!prefix || !*prefix) {
813 if (output_directory)
814 return output_directory;
815 /* The user did not explicitly ask for "./" */
816 outdir_offset = 2;
817 return "./";
820 outdir_offset = strlen(prefix);
821 if (!output_directory)
822 return prefix;
824 return xstrdup(prefix_filename(prefix, outdir_offset,
825 output_directory));
828 static const char * const builtin_format_patch_usage[] = {
829 "git format-patch [options] [<since> | <revision range>]",
830 NULL
833 static int keep_subject = 0;
835 static int keep_callback(const struct option *opt, const char *arg, int unset)
837 ((struct rev_info *)opt->value)->total = -1;
838 keep_subject = 1;
839 return 0;
842 static int subject_prefix = 0;
844 static int subject_prefix_callback(const struct option *opt, const char *arg,
845 int unset)
847 subject_prefix = 1;
848 ((struct rev_info *)opt->value)->subject_prefix = arg;
849 return 0;
852 static int numbered_cmdline_opt = 0;
854 static int numbered_callback(const struct option *opt, const char *arg,
855 int unset)
857 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
858 if (unset)
859 auto_number = 0;
860 return 0;
863 static int no_numbered_callback(const struct option *opt, const char *arg,
864 int unset)
866 return numbered_callback(opt, arg, 1);
869 static int output_directory_callback(const struct option *opt, const char *arg,
870 int unset)
872 const char **dir = (const char **)opt->value;
873 if (*dir)
874 die("Two output directories?");
875 *dir = arg;
876 return 0;
879 static int thread_callback(const struct option *opt, const char *arg, int unset)
881 int *thread = (int *)opt->value;
882 if (unset)
883 *thread = 0;
884 else if (!arg || !strcmp(arg, "shallow"))
885 *thread = THREAD_SHALLOW;
886 else if (!strcmp(arg, "deep"))
887 *thread = THREAD_DEEP;
888 else
889 return 1;
890 return 0;
893 static int attach_callback(const struct option *opt, const char *arg, int unset)
895 struct rev_info *rev = (struct rev_info *)opt->value;
896 if (unset)
897 rev->mime_boundary = NULL;
898 else if (arg)
899 rev->mime_boundary = arg;
900 else
901 rev->mime_boundary = git_version_string;
902 rev->no_inline = unset ? 0 : 1;
903 return 0;
906 static int inline_callback(const struct option *opt, const char *arg, int unset)
908 struct rev_info *rev = (struct rev_info *)opt->value;
909 if (unset)
910 rev->mime_boundary = NULL;
911 else if (arg)
912 rev->mime_boundary = arg;
913 else
914 rev->mime_boundary = git_version_string;
915 rev->no_inline = 0;
916 return 0;
919 static int header_callback(const struct option *opt, const char *arg, int unset)
921 if (unset) {
922 string_list_clear(&extra_hdr, 0);
923 string_list_clear(&extra_to, 0);
924 string_list_clear(&extra_cc, 0);
925 } else {
926 add_header(arg);
928 return 0;
931 static int to_callback(const struct option *opt, const char *arg, int unset)
933 if (unset)
934 string_list_clear(&extra_to, 0);
935 else
936 string_list_append(arg, &extra_to);
937 return 0;
940 static int cc_callback(const struct option *opt, const char *arg, int unset)
942 if (unset)
943 string_list_clear(&extra_cc, 0);
944 else
945 string_list_append(arg, &extra_cc);
946 return 0;
949 int cmd_format_patch(int argc, const char **argv, const char *prefix)
951 struct commit *commit;
952 struct commit **list = NULL;
953 struct rev_info rev;
954 struct setup_revision_opt s_r_opt;
955 int nr = 0, total, i;
956 int use_stdout = 0;
957 int start_number = -1;
958 int numbered_files = 0; /* _just_ numbers */
959 int ignore_if_in_upstream = 0;
960 int cover_letter = 0;
961 int boundary_count = 0;
962 int no_binary_diff = 0;
963 struct commit *origin = NULL, *head = NULL;
964 const char *in_reply_to = NULL;
965 struct patch_ids ids;
966 char *add_signoff = NULL;
967 struct strbuf buf = STRBUF_INIT;
968 int use_patch_format = 0;
969 const struct option builtin_format_patch_options[] = {
970 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
971 "use [PATCH n/m] even with a single patch",
972 PARSE_OPT_NOARG, numbered_callback },
973 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
974 "use [PATCH] even with multiple patches",
975 PARSE_OPT_NOARG, no_numbered_callback },
976 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
977 OPT_BOOLEAN(0, "stdout", &use_stdout,
978 "print patches to standard out"),
979 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
980 "generate a cover letter"),
981 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
982 "use simple number sequence for output file names"),
983 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
984 "use <sfx> instead of '.patch'"),
985 OPT_INTEGER(0, "start-number", &start_number,
986 "start numbering patches at <n> instead of 1"),
987 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
988 "Use [<prefix>] instead of [PATCH]",
989 PARSE_OPT_NONEG, subject_prefix_callback },
990 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
991 "dir", "store resulting files in <dir>",
992 PARSE_OPT_NONEG, output_directory_callback },
993 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
994 "don't strip/add [PATCH]",
995 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
996 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
997 "don't output binary diffs"),
998 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
999 "don't include a patch matching a commit upstream"),
1000 { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
1001 "show patch format instead of default (patch + stat)",
1002 PARSE_OPT_NONEG | PARSE_OPT_NOARG },
1003 OPT_GROUP("Messaging"),
1004 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
1005 "add email header", 0, header_callback },
1006 { OPTION_CALLBACK, 0, "to", NULL, "email", "add To: header",
1007 0, to_callback },
1008 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
1009 0, cc_callback },
1010 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
1011 "make first mail a reply to <message-id>"),
1012 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
1013 "attach the patch", PARSE_OPT_OPTARG,
1014 attach_callback },
1015 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
1016 "inline the patch",
1017 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1018 inline_callback },
1019 { OPTION_CALLBACK, 0, "thread", &thread, "style",
1020 "enable message threading, styles: shallow, deep",
1021 PARSE_OPT_OPTARG, thread_callback },
1022 OPT_END()
1025 extra_hdr.strdup_strings = 1;
1026 extra_to.strdup_strings = 1;
1027 extra_cc.strdup_strings = 1;
1028 git_config(git_format_config, NULL);
1029 init_revisions(&rev, prefix);
1030 rev.commit_format = CMIT_FMT_EMAIL;
1031 rev.verbose_header = 1;
1032 rev.diff = 1;
1033 rev.combine_merges = 0;
1034 rev.ignore_merges = 1;
1035 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1036 rev.subject_prefix = fmt_patch_subject_prefix;
1037 memset(&s_r_opt, 0, sizeof(s_r_opt));
1038 s_r_opt.def = "HEAD";
1040 if (default_attach) {
1041 rev.mime_boundary = default_attach;
1042 rev.no_inline = 1;
1046 * Parse the arguments before setup_revisions(), or something
1047 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1048 * possibly a valid SHA1.
1050 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1051 builtin_format_patch_usage,
1052 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1053 PARSE_OPT_KEEP_DASHDASH);
1055 if (do_signoff) {
1056 const char *committer;
1057 const char *endpos;
1058 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
1059 endpos = strchr(committer, '>');
1060 if (!endpos)
1061 die("bogus committer info %s", committer);
1062 add_signoff = xmemdupz(committer, endpos - committer + 1);
1065 for (i = 0; i < extra_hdr.nr; i++) {
1066 strbuf_addstr(&buf, extra_hdr.items[i].string);
1067 strbuf_addch(&buf, '\n');
1070 if (extra_to.nr)
1071 strbuf_addstr(&buf, "To: ");
1072 for (i = 0; i < extra_to.nr; i++) {
1073 if (i)
1074 strbuf_addstr(&buf, " ");
1075 strbuf_addstr(&buf, extra_to.items[i].string);
1076 if (i + 1 < extra_to.nr)
1077 strbuf_addch(&buf, ',');
1078 strbuf_addch(&buf, '\n');
1081 if (extra_cc.nr)
1082 strbuf_addstr(&buf, "Cc: ");
1083 for (i = 0; i < extra_cc.nr; i++) {
1084 if (i)
1085 strbuf_addstr(&buf, " ");
1086 strbuf_addstr(&buf, extra_cc.items[i].string);
1087 if (i + 1 < extra_cc.nr)
1088 strbuf_addch(&buf, ',');
1089 strbuf_addch(&buf, '\n');
1092 rev.extra_headers = strbuf_detach(&buf, NULL);
1094 if (start_number < 0)
1095 start_number = 1;
1098 * If numbered is set solely due to format.numbered in config,
1099 * and it would conflict with --keep-subject (-k) from the
1100 * command line, reset "numbered".
1102 if (numbered && keep_subject && !numbered_cmdline_opt)
1103 numbered = 0;
1105 if (numbered && keep_subject)
1106 die ("-n and -k are mutually exclusive.");
1107 if (keep_subject && subject_prefix)
1108 die ("--subject-prefix and -k are mutually exclusive.");
1110 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1111 if (argc > 1)
1112 die ("unrecognized argument: %s", argv[1]);
1114 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1115 die("--name-only does not make sense");
1116 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1117 die("--name-status does not make sense");
1118 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1119 die("--check does not make sense");
1121 if (!use_patch_format &&
1122 (!rev.diffopt.output_format ||
1123 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1124 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1126 /* Always generate a patch */
1127 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1129 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1130 DIFF_OPT_SET(&rev.diffopt, BINARY);
1132 if (rev.show_notes)
1133 init_display_notes(&rev.notes_opt);
1135 if (!use_stdout)
1136 output_directory = set_outdir(prefix, output_directory);
1138 if (output_directory) {
1139 if (use_stdout)
1140 die("standard output, or directory, which one?");
1141 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1142 die_errno("Could not create directory '%s'",
1143 output_directory);
1146 if (rev.pending.nr == 1) {
1147 if (rev.max_count < 0 && !rev.show_root_diff) {
1149 * This is traditional behaviour of "git format-patch
1150 * origin" that prepares what the origin side still
1151 * does not have.
1153 rev.pending.objects[0].item->flags |= UNINTERESTING;
1154 add_head_to_pending(&rev);
1157 * Otherwise, it is "format-patch -22 HEAD", and/or
1158 * "format-patch --root HEAD". The user wants
1159 * get_revision() to do the usual traversal.
1164 * We cannot move this anywhere earlier because we do want to
1165 * know if --root was given explicitly from the command line.
1167 rev.show_root_diff = 1;
1169 if (cover_letter) {
1170 /* remember the range */
1171 int i;
1172 for (i = 0; i < rev.pending.nr; i++) {
1173 struct object *o = rev.pending.objects[i].item;
1174 if (!(o->flags & UNINTERESTING))
1175 head = (struct commit *)o;
1177 /* We can't generate a cover letter without any patches */
1178 if (!head)
1179 return 0;
1182 if (ignore_if_in_upstream) {
1183 /* Don't say anything if head and upstream are the same. */
1184 if (rev.pending.nr == 2) {
1185 struct object_array_entry *o = rev.pending.objects;
1186 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1187 return 0;
1189 get_patch_ids(&rev, &ids, prefix);
1192 if (!use_stdout)
1193 realstdout = xfdopen(xdup(1), "w");
1195 if (prepare_revision_walk(&rev))
1196 die("revision walk setup failed");
1197 rev.boundary = 1;
1198 while ((commit = get_revision(&rev)) != NULL) {
1199 if (commit->object.flags & BOUNDARY) {
1200 boundary_count++;
1201 origin = (boundary_count == 1) ? commit : NULL;
1202 continue;
1205 /* ignore merges */
1206 if (commit->parents && commit->parents->next)
1207 continue;
1209 if (ignore_if_in_upstream &&
1210 has_commit_patch_id(commit, &ids))
1211 continue;
1213 nr++;
1214 list = xrealloc(list, nr * sizeof(list[0]));
1215 list[nr - 1] = commit;
1217 total = nr;
1218 if (!keep_subject && auto_number && total > 1)
1219 numbered = 1;
1220 if (numbered)
1221 rev.total = total + start_number - 1;
1222 if (in_reply_to || thread || cover_letter)
1223 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1224 if (in_reply_to) {
1225 const char *msgid = clean_message_id(in_reply_to);
1226 string_list_append(msgid, rev.ref_message_ids);
1228 rev.numbered_files = numbered_files;
1229 rev.patch_suffix = fmt_patch_suffix;
1230 if (cover_letter) {
1231 if (thread)
1232 gen_message_id(&rev, "cover");
1233 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1234 origin, nr, list, head);
1235 total++;
1236 start_number--;
1238 rev.add_signoff = add_signoff;
1239 while (0 <= --nr) {
1240 int shown;
1241 commit = list[nr];
1242 rev.nr = total - nr + (start_number - 1);
1243 /* Make the second and subsequent mails replies to the first */
1244 if (thread) {
1245 /* Have we already had a message ID? */
1246 if (rev.message_id) {
1248 * For deep threading: make every mail
1249 * a reply to the previous one, no
1250 * matter what other options are set.
1252 * For shallow threading:
1254 * Without --cover-letter and
1255 * --in-reply-to, make every mail a
1256 * reply to the one before.
1258 * With --in-reply-to but no
1259 * --cover-letter, make every mail a
1260 * reply to the <reply-to>.
1262 * With --cover-letter, make every
1263 * mail but the cover letter a reply
1264 * to the cover letter. The cover
1265 * letter is a reply to the
1266 * --in-reply-to, if specified.
1268 if (thread == THREAD_SHALLOW
1269 && rev.ref_message_ids->nr > 0
1270 && (!cover_letter || rev.nr > 1))
1271 free(rev.message_id);
1272 else
1273 string_list_append(rev.message_id,
1274 rev.ref_message_ids);
1276 gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1279 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1280 &rev))
1281 die("Failed to create output files");
1282 shown = log_tree_commit(&rev, commit);
1283 free(commit->buffer);
1284 commit->buffer = NULL;
1286 /* We put one extra blank line between formatted
1287 * patches and this flag is used by log-tree code
1288 * to see if it needs to emit a LF before showing
1289 * the log; when using one file per patch, we do
1290 * not want the extra blank line.
1292 if (!use_stdout)
1293 rev.shown_one = 0;
1294 if (shown) {
1295 if (rev.mime_boundary)
1296 printf("\n--%s%s--\n\n\n",
1297 mime_boundary_leader,
1298 rev.mime_boundary);
1299 else
1300 printf("-- \n%s\n\n", git_version_string);
1302 if (!use_stdout)
1303 fclose(stdout);
1305 free(list);
1306 string_list_clear(&extra_to, 0);
1307 string_list_clear(&extra_cc, 0);
1308 string_list_clear(&extra_hdr, 0);
1309 if (ignore_if_in_upstream)
1310 free_patch_ids(&ids);
1311 return 0;
1314 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1316 unsigned char sha1[20];
1317 if (get_sha1(arg, sha1) == 0) {
1318 struct commit *commit = lookup_commit_reference(sha1);
1319 if (commit) {
1320 commit->object.flags |= flags;
1321 add_pending_object(revs, &commit->object, arg);
1322 return 0;
1325 return -1;
1328 static const char * const cherry_usage[] = {
1329 "git cherry [-v] [<upstream> [<head> [<limit>]]]",
1330 NULL
1333 int cmd_cherry(int argc, const char **argv, const char *prefix)
1335 struct rev_info revs;
1336 struct patch_ids ids;
1337 struct commit *commit;
1338 struct commit_list *list = NULL;
1339 struct branch *current_branch;
1340 const char *upstream;
1341 const char *head = "HEAD";
1342 const char *limit = NULL;
1343 int verbose = 0, abbrev = 0;
1345 struct option options[] = {
1346 OPT__ABBREV(&abbrev),
1347 OPT__VERBOSE(&verbose),
1348 OPT_END()
1351 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
1353 switch (argc) {
1354 case 3:
1355 limit = argv[2];
1356 /* FALLTHROUGH */
1357 case 2:
1358 head = argv[1];
1359 /* FALLTHROUGH */
1360 case 1:
1361 upstream = argv[0];
1362 break;
1363 default:
1364 current_branch = branch_get(NULL);
1365 if (!current_branch || !current_branch->merge
1366 || !current_branch->merge[0]
1367 || !current_branch->merge[0]->dst) {
1368 fprintf(stderr, "Could not find a tracked"
1369 " remote branch, please"
1370 " specify <upstream> manually.\n");
1371 usage_with_options(cherry_usage, options);
1374 upstream = current_branch->merge[0]->dst;
1377 init_revisions(&revs, prefix);
1378 revs.diff = 1;
1379 revs.combine_merges = 0;
1380 revs.ignore_merges = 1;
1381 DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1383 if (add_pending_commit(head, &revs, 0))
1384 die("Unknown commit %s", head);
1385 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1386 die("Unknown commit %s", upstream);
1388 /* Don't say anything if head and upstream are the same. */
1389 if (revs.pending.nr == 2) {
1390 struct object_array_entry *o = revs.pending.objects;
1391 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1392 return 0;
1395 get_patch_ids(&revs, &ids, prefix);
1397 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1398 die("Unknown commit %s", limit);
1400 /* reverse the list of commits */
1401 if (prepare_revision_walk(&revs))
1402 die("revision walk setup failed");
1403 while ((commit = get_revision(&revs)) != NULL) {
1404 /* ignore merges */
1405 if (commit->parents && commit->parents->next)
1406 continue;
1408 commit_list_insert(commit, &list);
1411 while (list) {
1412 char sign = '+';
1414 commit = list->item;
1415 if (has_commit_patch_id(commit, &ids))
1416 sign = '-';
1418 if (verbose) {
1419 struct strbuf buf = STRBUF_INIT;
1420 struct pretty_print_context ctx = {0};
1421 pretty_print_commit(CMIT_FMT_ONELINE, commit,
1422 &buf, &ctx);
1423 printf("%c %s %s\n", sign,
1424 find_unique_abbrev(commit->object.sha1, abbrev),
1425 buf.buf);
1426 strbuf_release(&buf);
1428 else {
1429 printf("%c %s\n", sign,
1430 find_unique_abbrev(commit->object.sha1, abbrev));
1433 list = list->next;
1436 free_patch_ids(&ids);
1437 return 0;