Code

notes: track whether notes_trees were changed at all
[git.git] / builtin-log.c
1 /*
2  * Builtin "git log" and related commands (show, whatchanged)
3  *
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)
36 {
37         int i;
38         int decoration_style = 0;
40         rev->abbrev = DEFAULT_ABBREV;
41         rev->commit_format = CMIT_FMT_DEFAULT;
42         if (fmt_pretty)
43                 get_commit_format(fmt_pretty, rev);
44         rev->verbose_header = 1;
45         DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
46         rev->show_root_diff = default_show_root;
47         rev->subject_prefix = fmt_patch_subject_prefix;
48         DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
50         if (default_date_mode)
51                 rev->date_mode = parse_date_format(default_date_mode);
53         /*
54          * Check for -h before setup_revisions(), or "git log -h" will
55          * fail when run without a git directory.
56          */
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;
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");
72         }
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);
91         }
92         if (decoration_style) {
93                 rev->show_decorations = 1;
94                 load_ref_decorations(decoration_style);
95         }
96 }
98 /*
99  * This gives a rough estimate for how many commits we
100  * will print out in the list.
101  */
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++;
112         }
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);
122         }
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;
142                         }
143                         log_tree_commit(revs, commit);
144                         i--;
145                         break;
146                 case commit_ignore:
147                         break;
148                 case commit_error:
149                         return;
150                 }
151                 list = list->next;
152         }
154         /* Did we already get enough commits for the early output? */
155         if (!i)
156                 return;
158         /*
159          * ..if no, then repeat it twice a second until we
160          * do.
161          *
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!
167          */
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;
182         /*
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.
188          */
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);
195         /*
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..
199          *
200          * This is a one-time-only trigger.
201          */
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);
227         /*
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
231          */
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;
238                 }
239                 free_commit_list(commit->parents);
240                 commit->parents = NULL;
241         }
242         if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
243             DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
244                 return 02;
245         }
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;
260         }
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;
268         git_config(git_log_config, NULL);
270         if (diff_use_color_default == -1)
271                 diff_use_color_default = git_use_color_default;
273         init_revisions(&rev, prefix);
274         rev.diff = 1;
275         rev.simplify_history = 0;
276         cmd_log_init(argc, argv, prefix, &rev);
277         if (!rev.diffopt.output_format)
278                 rev.diffopt.output_format = DIFF_FORMAT_RAW;
279         return cmd_log_walk(&rev);
282 static void show_tagger(char *buf, int len, struct rev_info *rev)
284         struct strbuf out = STRBUF_INIT;
286         pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
287                 git_log_output_encoding ?
288                 git_log_output_encoding: git_commit_encoding);
289         printf("%s", out.buf);
290         strbuf_release(&out);
293 static int show_object(const unsigned char *sha1, int show_tag_object,
294         struct rev_info *rev)
296         unsigned long size;
297         enum object_type type;
298         char *buf = read_sha1_file(sha1, &type, &size);
299         int offset = 0;
301         if (!buf)
302                 return error("Could not read object %s", sha1_to_hex(sha1));
304         if (show_tag_object)
305                 while (offset < size && buf[offset] != '\n') {
306                         int new_offset = offset + 1;
307                         while (new_offset < size && buf[new_offset++] != '\n')
308                                 ; /* do nothing */
309                         if (!prefixcmp(buf + offset, "tagger "))
310                                 show_tagger(buf + offset + 7,
311                                             new_offset - offset - 7, rev);
312                         offset = new_offset;
313                 }
315         if (offset < size)
316                 fwrite(buf + offset, size - offset, 1, stdout);
317         free(buf);
318         return 0;
321 static int show_tree_object(const unsigned char *sha1,
322                 const char *base, int baselen,
323                 const char *pathname, unsigned mode, int stage, void *context)
325         printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
326         return 0;
329 int cmd_show(int argc, const char **argv, const char *prefix)
331         struct rev_info rev;
332         struct object_array_entry *objects;
333         int i, count, ret = 0;
335         git_config(git_log_config, NULL);
337         if (diff_use_color_default == -1)
338                 diff_use_color_default = git_use_color_default;
340         init_revisions(&rev, prefix);
341         rev.diff = 1;
342         rev.combine_merges = 1;
343         rev.dense_combined_merges = 1;
344         rev.always_show_header = 1;
345         rev.ignore_merges = 0;
346         rev.no_walk = 1;
347         cmd_log_init(argc, argv, prefix, &rev);
349         count = rev.pending.nr;
350         objects = rev.pending.objects;
351         for (i = 0; i < count && !ret; i++) {
352                 struct object *o = objects[i].item;
353                 const char *name = objects[i].name;
354                 switch (o->type) {
355                 case OBJ_BLOB:
356                         ret = show_object(o->sha1, 0, NULL);
357                         break;
358                 case OBJ_TAG: {
359                         struct tag *t = (struct tag *)o;
361                         if (rev.shown_one)
362                                 putchar('\n');
363                         printf("%stag %s%s\n",
364                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
365                                         t->tag,
366                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
367                         ret = show_object(o->sha1, 1, &rev);
368                         rev.shown_one = 1;
369                         if (ret)
370                                 break;
371                         o = parse_object(t->tagged->sha1);
372                         if (!o)
373                                 ret = error("Could not read object %s",
374                                             sha1_to_hex(t->tagged->sha1));
375                         objects[i].item = o;
376                         i--;
377                         break;
378                 }
379                 case OBJ_TREE:
380                         if (rev.shown_one)
381                                 putchar('\n');
382                         printf("%stree %s%s\n\n",
383                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
384                                         name,
385                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
386                         read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
387                                         show_tree_object, NULL);
388                         rev.shown_one = 1;
389                         break;
390                 case OBJ_COMMIT:
391                         rev.pending.nr = rev.pending.alloc = 0;
392                         rev.pending.objects = NULL;
393                         add_object_array(o, name, &rev.pending);
394                         ret = cmd_log_walk(&rev);
395                         break;
396                 default:
397                         ret = error("Unknown type: %d", o->type);
398                 }
399         }
400         free(objects);
401         return ret;
404 /*
405  * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
406  */
407 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
409         struct rev_info rev;
411         git_config(git_log_config, NULL);
413         if (diff_use_color_default == -1)
414                 diff_use_color_default = git_use_color_default;
416         init_revisions(&rev, prefix);
417         init_reflog_walk(&rev.reflog_info);
418         rev.abbrev_commit = 1;
419         rev.verbose_header = 1;
420         cmd_log_init(argc, argv, prefix, &rev);
422         /*
423          * This means that we override whatever commit format the user gave
424          * on the cmd line.  Sad, but cmd_log_init() currently doesn't
425          * allow us to set a different default.
426          */
427         rev.commit_format = CMIT_FMT_ONELINE;
428         rev.use_terminator = 1;
429         rev.always_show_header = 1;
431         /*
432          * We get called through "git reflog", so unlike the other log
433          * routines, we need to set up our pager manually..
434          */
435         setup_pager();
437         return cmd_log_walk(&rev);
440 int cmd_log(int argc, const char **argv, const char *prefix)
442         struct rev_info rev;
444         git_config(git_log_config, NULL);
446         if (diff_use_color_default == -1)
447                 diff_use_color_default = git_use_color_default;
449         init_revisions(&rev, prefix);
450         rev.always_show_header = 1;
451         cmd_log_init(argc, argv, prefix, &rev);
452         return cmd_log_walk(&rev);
455 /* format-patch */
457 static const char *fmt_patch_suffix = ".patch";
458 static int numbered = 0;
459 static int auto_number = 1;
461 static char *default_attach = NULL;
463 static char **extra_hdr;
464 static int extra_hdr_nr;
465 static int extra_hdr_alloc;
467 static char **extra_to;
468 static int extra_to_nr;
469 static int extra_to_alloc;
471 static char **extra_cc;
472 static int extra_cc_nr;
473 static int extra_cc_alloc;
475 static void add_header(const char *value)
477         int len = strlen(value);
478         while (len && value[len - 1] == '\n')
479                 len--;
480         if (!strncasecmp(value, "to: ", 4)) {
481                 ALLOC_GROW(extra_to, extra_to_nr + 1, extra_to_alloc);
482                 extra_to[extra_to_nr++] = xstrndup(value + 4, len - 4);
483                 return;
484         }
485         if (!strncasecmp(value, "cc: ", 4)) {
486                 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
487                 extra_cc[extra_cc_nr++] = xstrndup(value + 4, len - 4);
488                 return;
489         }
490         ALLOC_GROW(extra_hdr, extra_hdr_nr + 1, extra_hdr_alloc);
491         extra_hdr[extra_hdr_nr++] = xstrndup(value, len);
494 #define THREAD_SHALLOW 1
495 #define THREAD_DEEP 2
496 static int thread = 0;
497 static int do_signoff = 0;
499 static int git_format_config(const char *var, const char *value, void *cb)
501         if (!strcmp(var, "format.headers")) {
502                 if (!value)
503                         die("format.headers without value");
504                 add_header(value);
505                 return 0;
506         }
507         if (!strcmp(var, "format.suffix"))
508                 return git_config_string(&fmt_patch_suffix, var, value);
509         if (!strcmp(var, "format.cc")) {
510                 if (!value)
511                         return config_error_nonbool(var);
512                 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
513                 extra_cc[extra_cc_nr++] = xstrdup(value);
514                 return 0;
515         }
516         if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
517                 return 0;
518         }
519         if (!strcmp(var, "format.numbered")) {
520                 if (value && !strcasecmp(value, "auto")) {
521                         auto_number = 1;
522                         return 0;
523                 }
524                 numbered = git_config_bool(var, value);
525                 auto_number = auto_number && numbered;
526                 return 0;
527         }
528         if (!strcmp(var, "format.attach")) {
529                 if (value && *value)
530                         default_attach = xstrdup(value);
531                 else
532                         default_attach = xstrdup(git_version_string);
533                 return 0;
534         }
535         if (!strcmp(var, "format.thread")) {
536                 if (value && !strcasecmp(value, "deep")) {
537                         thread = THREAD_DEEP;
538                         return 0;
539                 }
540                 if (value && !strcasecmp(value, "shallow")) {
541                         thread = THREAD_SHALLOW;
542                         return 0;
543                 }
544                 thread = git_config_bool(var, value) && THREAD_SHALLOW;
545                 return 0;
546         }
547         if (!strcmp(var, "format.signoff")) {
548                 do_signoff = git_config_bool(var, value);
549                 return 0;
550         }
552         return git_log_config(var, value, cb);
555 static FILE *realstdout = NULL;
556 static const char *output_directory = NULL;
557 static int outdir_offset;
559 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
561         struct strbuf filename = STRBUF_INIT;
562         int suffix_len = strlen(fmt_patch_suffix) + 1;
564         if (output_directory) {
565                 strbuf_addstr(&filename, output_directory);
566                 if (filename.len >=
567                     PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
568                         return error("name of output directory is too long");
569                 if (filename.buf[filename.len - 1] != '/')
570                         strbuf_addch(&filename, '/');
571         }
573         get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
575         if (!DIFF_OPT_TST(&rev->diffopt, QUICK))
576                 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
578         if (freopen(filename.buf, "w", stdout) == NULL)
579                 return error("Cannot open patch file %s", filename.buf);
581         strbuf_release(&filename);
582         return 0;
585 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
587         struct rev_info check_rev;
588         struct commit *commit;
589         struct object *o1, *o2;
590         unsigned flags1, flags2;
592         if (rev->pending.nr != 2)
593                 die("Need exactly one range.");
595         o1 = rev->pending.objects[0].item;
596         flags1 = o1->flags;
597         o2 = rev->pending.objects[1].item;
598         flags2 = o2->flags;
600         if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
601                 die("Not a range.");
603         init_patch_ids(ids);
605         /* given a range a..b get all patch ids for b..a */
606         init_revisions(&check_rev, prefix);
607         o1->flags ^= UNINTERESTING;
608         o2->flags ^= UNINTERESTING;
609         add_pending_object(&check_rev, o1, "o1");
610         add_pending_object(&check_rev, o2, "o2");
611         if (prepare_revision_walk(&check_rev))
612                 die("revision walk setup failed");
614         while ((commit = get_revision(&check_rev)) != NULL) {
615                 /* ignore merges */
616                 if (commit->parents && commit->parents->next)
617                         continue;
619                 add_commit_patch_id(commit, ids);
620         }
622         /* reset for next revision walk */
623         clear_commit_marks((struct commit *)o1,
624                         SEEN | UNINTERESTING | SHOWN | ADDED);
625         clear_commit_marks((struct commit *)o2,
626                         SEEN | UNINTERESTING | SHOWN | ADDED);
627         o1->flags = flags1;
628         o2->flags = flags2;
631 static void gen_message_id(struct rev_info *info, char *base)
633         const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
634         const char *email_start = strrchr(committer, '<');
635         const char *email_end = strrchr(committer, '>');
636         struct strbuf buf = STRBUF_INIT;
637         if (!email_start || !email_end || email_start > email_end - 1)
638                 die("Could not extract email from committer identity.");
639         strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
640                     (unsigned long) time(NULL),
641                     (int)(email_end - email_start - 1), email_start + 1);
642         info->message_id = strbuf_detach(&buf, NULL);
645 static void make_cover_letter(struct rev_info *rev, int use_stdout,
646                               int numbered, int numbered_files,
647                               struct commit *origin,
648                               int nr, struct commit **list, struct commit *head)
650         const char *committer;
651         const char *subject_start = NULL;
652         const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
653         const char *msg;
654         const char *extra_headers = rev->extra_headers;
655         struct shortlog log;
656         struct strbuf sb = STRBUF_INIT;
657         int i;
658         const char *encoding = "UTF-8";
659         struct diff_options opts;
660         int need_8bit_cte = 0;
661         struct commit *commit = NULL;
663         if (rev->commit_format != CMIT_FMT_EMAIL)
664                 die("Cover letter needs email format");
666         committer = git_committer_info(0);
668         if (!numbered_files) {
669                 /*
670                  * We fake a commit for the cover letter so we get the filename
671                  * desired.
672                  */
673                 commit = xcalloc(1, sizeof(*commit));
674                 commit->buffer = xmalloc(400);
675                 snprintf(commit->buffer, 400,
676                         "tree 0000000000000000000000000000000000000000\n"
677                         "parent %s\n"
678                         "author %s\n"
679                         "committer %s\n\n"
680                         "cover letter\n",
681                         sha1_to_hex(head->object.sha1), committer, committer);
682         }
684         if (!use_stdout && reopen_stdout(commit, rev))
685                 return;
687         if (commit) {
689                 free(commit->buffer);
690                 free(commit);
691         }
693         log_write_email_headers(rev, head, &subject_start, &extra_headers,
694                                 &need_8bit_cte);
696         for (i = 0; !need_8bit_cte && i < nr; i++)
697                 if (has_non_ascii(list[i]->buffer))
698                         need_8bit_cte = 1;
700         msg = body;
701         pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
702                      encoding);
703         pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
704                       encoding, need_8bit_cte);
705         pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
706         printf("%s\n", sb.buf);
708         strbuf_release(&sb);
710         shortlog_init(&log);
711         log.wrap_lines = 1;
712         log.wrap = 72;
713         log.in1 = 2;
714         log.in2 = 4;
715         for (i = 0; i < nr; i++)
716                 shortlog_add_commit(&log, list[i]);
718         shortlog_output(&log);
720         /*
721          * We can only do diffstat with a unique reference point
722          */
723         if (!origin)
724                 return;
726         memcpy(&opts, &rev->diffopt, sizeof(opts));
727         opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
729         diff_setup_done(&opts);
731         diff_tree_sha1(origin->tree->object.sha1,
732                        head->tree->object.sha1,
733                        "", &opts);
734         diffcore_std(&opts);
735         diff_flush(&opts);
737         printf("\n");
740 static const char *clean_message_id(const char *msg_id)
742         char ch;
743         const char *a, *z, *m;
745         m = msg_id;
746         while ((ch = *m) && (isspace(ch) || (ch == '<')))
747                 m++;
748         a = m;
749         z = NULL;
750         while ((ch = *m)) {
751                 if (!isspace(ch) && (ch != '>'))
752                         z = m;
753                 m++;
754         }
755         if (!z)
756                 die("insane in-reply-to: %s", msg_id);
757         if (++z == m)
758                 return a;
759         return xmemdupz(a, z - a);
762 static const char *set_outdir(const char *prefix, const char *output_directory)
764         if (output_directory && is_absolute_path(output_directory))
765                 return output_directory;
767         if (!prefix || !*prefix) {
768                 if (output_directory)
769                         return output_directory;
770                 /* The user did not explicitly ask for "./" */
771                 outdir_offset = 2;
772                 return "./";
773         }
775         outdir_offset = strlen(prefix);
776         if (!output_directory)
777                 return prefix;
779         return xstrdup(prefix_filename(prefix, outdir_offset,
780                                        output_directory));
783 static const char * const builtin_format_patch_usage[] = {
784         "git format-patch [options] [<since> | <revision range>]",
785         NULL
786 };
788 static int keep_subject = 0;
790 static int keep_callback(const struct option *opt, const char *arg, int unset)
792         ((struct rev_info *)opt->value)->total = -1;
793         keep_subject = 1;
794         return 0;
797 static int subject_prefix = 0;
799 static int subject_prefix_callback(const struct option *opt, const char *arg,
800                             int unset)
802         subject_prefix = 1;
803         ((struct rev_info *)opt->value)->subject_prefix = arg;
804         return 0;
807 static int numbered_cmdline_opt = 0;
809 static int numbered_callback(const struct option *opt, const char *arg,
810                              int unset)
812         *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
813         if (unset)
814                 auto_number =  0;
815         return 0;
818 static int no_numbered_callback(const struct option *opt, const char *arg,
819                                 int unset)
821         return numbered_callback(opt, arg, 1);
824 static int output_directory_callback(const struct option *opt, const char *arg,
825                               int unset)
827         const char **dir = (const char **)opt->value;
828         if (*dir)
829                 die("Two output directories?");
830         *dir = arg;
831         return 0;
834 static int thread_callback(const struct option *opt, const char *arg, int unset)
836         int *thread = (int *)opt->value;
837         if (unset)
838                 *thread = 0;
839         else if (!arg || !strcmp(arg, "shallow"))
840                 *thread = THREAD_SHALLOW;
841         else if (!strcmp(arg, "deep"))
842                 *thread = THREAD_DEEP;
843         else
844                 return 1;
845         return 0;
848 static int attach_callback(const struct option *opt, const char *arg, int unset)
850         struct rev_info *rev = (struct rev_info *)opt->value;
851         if (unset)
852                 rev->mime_boundary = NULL;
853         else if (arg)
854                 rev->mime_boundary = arg;
855         else
856                 rev->mime_boundary = git_version_string;
857         rev->no_inline = unset ? 0 : 1;
858         return 0;
861 static int inline_callback(const struct option *opt, const char *arg, int unset)
863         struct rev_info *rev = (struct rev_info *)opt->value;
864         if (unset)
865                 rev->mime_boundary = NULL;
866         else if (arg)
867                 rev->mime_boundary = arg;
868         else
869                 rev->mime_boundary = git_version_string;
870         rev->no_inline = 0;
871         return 0;
874 static int header_callback(const struct option *opt, const char *arg, int unset)
876         add_header(arg);
877         return 0;
880 static int cc_callback(const struct option *opt, const char *arg, int unset)
882         ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
883         extra_cc[extra_cc_nr++] = xstrdup(arg);
884         return 0;
887 int cmd_format_patch(int argc, const char **argv, const char *prefix)
889         struct commit *commit;
890         struct commit **list = NULL;
891         struct rev_info rev;
892         int nr = 0, total, i;
893         int use_stdout = 0;
894         int start_number = -1;
895         int numbered_files = 0;         /* _just_ numbers */
896         int ignore_if_in_upstream = 0;
897         int cover_letter = 0;
898         int boundary_count = 0;
899         int no_binary_diff = 0;
900         struct commit *origin = NULL, *head = NULL;
901         const char *in_reply_to = NULL;
902         struct patch_ids ids;
903         char *add_signoff = NULL;
904         struct strbuf buf = STRBUF_INIT;
905         int use_patch_format = 0;
906         const struct option builtin_format_patch_options[] = {
907                 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
908                             "use [PATCH n/m] even with a single patch",
909                             PARSE_OPT_NOARG, numbered_callback },
910                 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
911                             "use [PATCH] even with multiple patches",
912                             PARSE_OPT_NOARG, no_numbered_callback },
913                 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
914                 OPT_BOOLEAN(0, "stdout", &use_stdout,
915                             "print patches to standard out"),
916                 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
917                             "generate a cover letter"),
918                 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
919                             "use simple number sequence for output file names"),
920                 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
921                             "use <sfx> instead of '.patch'"),
922                 OPT_INTEGER(0, "start-number", &start_number,
923                             "start numbering patches at <n> instead of 1"),
924                 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
925                             "Use [<prefix>] instead of [PATCH]",
926                             PARSE_OPT_NONEG, subject_prefix_callback },
927                 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
928                             "dir", "store resulting files in <dir>",
929                             PARSE_OPT_NONEG, output_directory_callback },
930                 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
931                             "don't strip/add [PATCH]",
932                             PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
933                 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
934                             "don't output binary diffs"),
935                 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
936                             "don't include a patch matching a commit upstream"),
937                 { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
938                   "show patch format instead of default (patch + stat)",
939                   PARSE_OPT_NONEG | PARSE_OPT_NOARG },
940                 OPT_GROUP("Messaging"),
941                 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
942                             "add email header", PARSE_OPT_NONEG,
943                             header_callback },
944                 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
945                             PARSE_OPT_NONEG, cc_callback },
946                 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
947                             "make first mail a reply to <message-id>"),
948                 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
949                             "attach the patch", PARSE_OPT_OPTARG,
950                             attach_callback },
951                 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
952                             "inline the patch",
953                             PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
954                             inline_callback },
955                 { OPTION_CALLBACK, 0, "thread", &thread, "style",
956                             "enable message threading, styles: shallow, deep",
957                             PARSE_OPT_OPTARG, thread_callback },
958                 OPT_END()
959         };
961         git_config(git_format_config, NULL);
962         init_revisions(&rev, prefix);
963         rev.commit_format = CMIT_FMT_EMAIL;
964         rev.verbose_header = 1;
965         rev.diff = 1;
966         rev.combine_merges = 0;
967         rev.ignore_merges = 1;
968         DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
970         rev.subject_prefix = fmt_patch_subject_prefix;
972         if (default_attach) {
973                 rev.mime_boundary = default_attach;
974                 rev.no_inline = 1;
975         }
977         /*
978          * Parse the arguments before setup_revisions(), or something
979          * like "git format-patch -o a123 HEAD^.." may fail; a123 is
980          * possibly a valid SHA1.
981          */
982         argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
983                              builtin_format_patch_usage,
984                              PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
985                              PARSE_OPT_KEEP_DASHDASH);
987         if (do_signoff) {
988                 const char *committer;
989                 const char *endpos;
990                 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
991                 endpos = strchr(committer, '>');
992                 if (!endpos)
993                         die("bogus committer info %s", committer);
994                 add_signoff = xmemdupz(committer, endpos - committer + 1);
995         }
997         for (i = 0; i < extra_hdr_nr; i++) {
998                 strbuf_addstr(&buf, extra_hdr[i]);
999                 strbuf_addch(&buf, '\n');
1000         }
1002         if (extra_to_nr)
1003                 strbuf_addstr(&buf, "To: ");
1004         for (i = 0; i < extra_to_nr; i++) {
1005                 if (i)
1006                         strbuf_addstr(&buf, "    ");
1007                 strbuf_addstr(&buf, extra_to[i]);
1008                 if (i + 1 < extra_to_nr)
1009                         strbuf_addch(&buf, ',');
1010                 strbuf_addch(&buf, '\n');
1011         }
1013         if (extra_cc_nr)
1014                 strbuf_addstr(&buf, "Cc: ");
1015         for (i = 0; i < extra_cc_nr; i++) {
1016                 if (i)
1017                         strbuf_addstr(&buf, "    ");
1018                 strbuf_addstr(&buf, extra_cc[i]);
1019                 if (i + 1 < extra_cc_nr)
1020                         strbuf_addch(&buf, ',');
1021                 strbuf_addch(&buf, '\n');
1022         }
1024         rev.extra_headers = strbuf_detach(&buf, NULL);
1026         if (start_number < 0)
1027                 start_number = 1;
1029         /*
1030          * If numbered is set solely due to format.numbered in config,
1031          * and it would conflict with --keep-subject (-k) from the
1032          * command line, reset "numbered".
1033          */
1034         if (numbered && keep_subject && !numbered_cmdline_opt)
1035                 numbered = 0;
1037         if (numbered && keep_subject)
1038                 die ("-n and -k are mutually exclusive.");
1039         if (keep_subject && subject_prefix)
1040                 die ("--subject-prefix and -k are mutually exclusive.");
1042         argc = setup_revisions(argc, argv, &rev, "HEAD");
1043         if (argc > 1)
1044                 die ("unrecognized argument: %s", argv[1]);
1046         if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1047                 die("--name-only does not make sense");
1048         if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1049                 die("--name-status does not make sense");
1050         if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1051                 die("--check does not make sense");
1053         if (!use_patch_format &&
1054                 (!rev.diffopt.output_format ||
1055                  rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1056                 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1058         /* Always generate a patch */
1059         rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1061         if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1062                 DIFF_OPT_SET(&rev.diffopt, BINARY);
1064         if (rev.show_notes)
1065                 init_display_notes(&rev.notes_opt);
1067         if (!use_stdout)
1068                 output_directory = set_outdir(prefix, output_directory);
1070         if (output_directory) {
1071                 if (use_stdout)
1072                         die("standard output, or directory, which one?");
1073                 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1074                         die_errno("Could not create directory '%s'",
1075                                   output_directory);
1076         }
1078         if (rev.pending.nr == 1) {
1079                 if (rev.max_count < 0 && !rev.show_root_diff) {
1080                         /*
1081                          * This is traditional behaviour of "git format-patch
1082                          * origin" that prepares what the origin side still
1083                          * does not have.
1084                          */
1085                         rev.pending.objects[0].item->flags |= UNINTERESTING;
1086                         add_head_to_pending(&rev);
1087                 }
1088                 /*
1089                  * Otherwise, it is "format-patch -22 HEAD", and/or
1090                  * "format-patch --root HEAD".  The user wants
1091                  * get_revision() to do the usual traversal.
1092                  */
1093         }
1095         /*
1096          * We cannot move this anywhere earlier because we do want to
1097          * know if --root was given explicitly from the comand line.
1098          */
1099         rev.show_root_diff = 1;
1101         if (cover_letter) {
1102                 /* remember the range */
1103                 int i;
1104                 for (i = 0; i < rev.pending.nr; i++) {
1105                         struct object *o = rev.pending.objects[i].item;
1106                         if (!(o->flags & UNINTERESTING))
1107                                 head = (struct commit *)o;
1108                 }
1109                 /* We can't generate a cover letter without any patches */
1110                 if (!head)
1111                         return 0;
1112         }
1114         if (ignore_if_in_upstream)
1115                 get_patch_ids(&rev, &ids, prefix);
1117         if (!use_stdout)
1118                 realstdout = xfdopen(xdup(1), "w");
1120         if (prepare_revision_walk(&rev))
1121                 die("revision walk setup failed");
1122         rev.boundary = 1;
1123         while ((commit = get_revision(&rev)) != NULL) {
1124                 if (commit->object.flags & BOUNDARY) {
1125                         boundary_count++;
1126                         origin = (boundary_count == 1) ? commit : NULL;
1127                         continue;
1128                 }
1130                 /* ignore merges */
1131                 if (commit->parents && commit->parents->next)
1132                         continue;
1134                 if (ignore_if_in_upstream &&
1135                                 has_commit_patch_id(commit, &ids))
1136                         continue;
1138                 nr++;
1139                 list = xrealloc(list, nr * sizeof(list[0]));
1140                 list[nr - 1] = commit;
1141         }
1142         total = nr;
1143         if (!keep_subject && auto_number && total > 1)
1144                 numbered = 1;
1145         if (numbered)
1146                 rev.total = total + start_number - 1;
1147         if (in_reply_to || thread || cover_letter)
1148                 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1149         if (in_reply_to) {
1150                 const char *msgid = clean_message_id(in_reply_to);
1151                 string_list_append(msgid, rev.ref_message_ids);
1152         }
1153         rev.numbered_files = numbered_files;
1154         rev.patch_suffix = fmt_patch_suffix;
1155         if (cover_letter) {
1156                 if (thread)
1157                         gen_message_id(&rev, "cover");
1158                 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1159                                   origin, nr, list, head);
1160                 total++;
1161                 start_number--;
1162         }
1163         rev.add_signoff = add_signoff;
1164         while (0 <= --nr) {
1165                 int shown;
1166                 commit = list[nr];
1167                 rev.nr = total - nr + (start_number - 1);
1168                 /* Make the second and subsequent mails replies to the first */
1169                 if (thread) {
1170                         /* Have we already had a message ID? */
1171                         if (rev.message_id) {
1172                                 /*
1173                                  * For deep threading: make every mail
1174                                  * a reply to the previous one, no
1175                                  * matter what other options are set.
1176                                  *
1177                                  * For shallow threading:
1178                                  *
1179                                  * Without --cover-letter and
1180                                  * --in-reply-to, make every mail a
1181                                  * reply to the one before.
1182                                  *
1183                                  * With --in-reply-to but no
1184                                  * --cover-letter, make every mail a
1185                                  * reply to the <reply-to>.
1186                                  *
1187                                  * With --cover-letter, make every
1188                                  * mail but the cover letter a reply
1189                                  * to the cover letter.  The cover
1190                                  * letter is a reply to the
1191                                  * --in-reply-to, if specified.
1192                                  */
1193                                 if (thread == THREAD_SHALLOW
1194                                     && rev.ref_message_ids->nr > 0
1195                                     && (!cover_letter || rev.nr > 1))
1196                                         free(rev.message_id);
1197                                 else
1198                                         string_list_append(rev.message_id,
1199                                                            rev.ref_message_ids);
1200                         }
1201                         gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1202                 }
1204                 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1205                                                  &rev))
1206                         die("Failed to create output files");
1207                 shown = log_tree_commit(&rev, commit);
1208                 free(commit->buffer);
1209                 commit->buffer = NULL;
1211                 /* We put one extra blank line between formatted
1212                  * patches and this flag is used by log-tree code
1213                  * to see if it needs to emit a LF before showing
1214                  * the log; when using one file per patch, we do
1215                  * not want the extra blank line.
1216                  */
1217                 if (!use_stdout)
1218                         rev.shown_one = 0;
1219                 if (shown) {
1220                         if (rev.mime_boundary)
1221                                 printf("\n--%s%s--\n\n\n",
1222                                        mime_boundary_leader,
1223                                        rev.mime_boundary);
1224                         else
1225                                 printf("-- \n%s\n\n", git_version_string);
1226                 }
1227                 if (!use_stdout)
1228                         fclose(stdout);
1229         }
1230         free(list);
1231         if (ignore_if_in_upstream)
1232                 free_patch_ids(&ids);
1233         return 0;
1236 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1238         unsigned char sha1[20];
1239         if (get_sha1(arg, sha1) == 0) {
1240                 struct commit *commit = lookup_commit_reference(sha1);
1241                 if (commit) {
1242                         commit->object.flags |= flags;
1243                         add_pending_object(revs, &commit->object, arg);
1244                         return 0;
1245                 }
1246         }
1247         return -1;
1250 static const char cherry_usage[] =
1251 "git cherry [-v] [<upstream> [<head> [<limit>]]]";
1252 int cmd_cherry(int argc, const char **argv, const char *prefix)
1254         struct rev_info revs;
1255         struct patch_ids ids;
1256         struct commit *commit;
1257         struct commit_list *list = NULL;
1258         struct branch *current_branch;
1259         const char *upstream;
1260         const char *head = "HEAD";
1261         const char *limit = NULL;
1262         int verbose = 0;
1264         if (argc > 1 && !strcmp(argv[1], "-v")) {
1265                 verbose = 1;
1266                 argc--;
1267                 argv++;
1268         }
1270         if (argc > 1 && !strcmp(argv[1], "-h"))
1271                 usage(cherry_usage);
1273         switch (argc) {
1274         case 4:
1275                 limit = argv[3];
1276                 /* FALLTHROUGH */
1277         case 3:
1278                 head = argv[2];
1279                 /* FALLTHROUGH */
1280         case 2:
1281                 upstream = argv[1];
1282                 break;
1283         default:
1284                 current_branch = branch_get(NULL);
1285                 if (!current_branch || !current_branch->merge
1286                                         || !current_branch->merge[0]
1287                                         || !current_branch->merge[0]->dst) {
1288                         fprintf(stderr, "Could not find a tracked"
1289                                         " remote branch, please"
1290                                         " specify <upstream> manually.\n");
1291                         usage(cherry_usage);
1292                 }
1294                 upstream = current_branch->merge[0]->dst;
1295         }
1297         init_revisions(&revs, prefix);
1298         revs.diff = 1;
1299         revs.combine_merges = 0;
1300         revs.ignore_merges = 1;
1301         DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1303         if (add_pending_commit(head, &revs, 0))
1304                 die("Unknown commit %s", head);
1305         if (add_pending_commit(upstream, &revs, UNINTERESTING))
1306                 die("Unknown commit %s", upstream);
1308         /* Don't say anything if head and upstream are the same. */
1309         if (revs.pending.nr == 2) {
1310                 struct object_array_entry *o = revs.pending.objects;
1311                 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1312                         return 0;
1313         }
1315         get_patch_ids(&revs, &ids, prefix);
1317         if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1318                 die("Unknown commit %s", limit);
1320         /* reverse the list of commits */
1321         if (prepare_revision_walk(&revs))
1322                 die("revision walk setup failed");
1323         while ((commit = get_revision(&revs)) != NULL) {
1324                 /* ignore merges */
1325                 if (commit->parents && commit->parents->next)
1326                         continue;
1328                 commit_list_insert(commit, &list);
1329         }
1331         while (list) {
1332                 char sign = '+';
1334                 commit = list->item;
1335                 if (has_commit_patch_id(commit, &ids))
1336                         sign = '-';
1338                 if (verbose) {
1339                         struct strbuf buf = STRBUF_INIT;
1340                         struct pretty_print_context ctx = {0};
1341                         pretty_print_commit(CMIT_FMT_ONELINE, commit,
1342                                             &buf, &ctx);
1343                         printf("%c %s %s\n", sign,
1344                                sha1_to_hex(commit->object.sha1), buf.buf);
1345                         strbuf_release(&buf);
1346                 }
1347                 else {
1348                         printf("%c %s\n", sign,
1349                                sha1_to_hex(commit->object.sha1));
1350                 }
1352                 list = list->next;
1353         }
1355         free_patch_ids(&ids);
1356         return 0;