Code

log --pretty/--oneline: ignore log.decorate
[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 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)
36 {
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;
44         }
45         if (!strcmp(value, "full"))
46                 return DECORATE_FULL_REFS;
47         else if (!strcmp(value, "short"))
48                 return DECORATE_SHORT_REFS;
49         return -1;
50 }
52 static void cmd_log_init(int argc, const char **argv, const char *prefix,
53                       struct rev_info *rev)
54 {
55         int i;
56         int decoration_given = 0;
58         rev->abbrev = DEFAULT_ABBREV;
59         rev->commit_format = CMIT_FMT_DEFAULT;
60         if (fmt_pretty)
61                 get_commit_format(fmt_pretty, rev);
62         rev->verbose_header = 1;
63         DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
64         rev->show_root_diff = default_show_root;
65         rev->subject_prefix = fmt_patch_subject_prefix;
66         DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
68         if (default_date_mode)
69                 rev->date_mode = parse_date_format(default_date_mode);
71         /*
72          * Check for -h before setup_revisions(), or "git log -h" will
73          * fail when run without a git directory.
74          */
75         if (argc == 2 && !strcmp(argv[1], "-h"))
76                 usage(builtin_log_usage);
77         argc = setup_revisions(argc, argv, rev, "HEAD");
79         if (!rev->show_notes_given && !rev->pretty_given)
80                 rev->show_notes = 1;
82         if (rev->diffopt.pickaxe || rev->diffopt.filter)
83                 rev->always_show_header = 0;
84         if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
85                 rev->always_show_header = 0;
86                 if (rev->diffopt.nr_paths != 1)
87                         usage("git logs can only follow renames on one pathname at a time");
88         }
89         for (i = 1; i < argc; i++) {
90                 const char *arg = argv[i];
91                 if (!strcmp(arg, "--decorate")) {
92                         decoration_style = DECORATE_SHORT_REFS;
93                         decoration_given = 1;
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                         decoration_given = 1;
100                 } else if (!strcmp(arg, "--no-decorate")) {
101                         decoration_style = 0;
102                 } else if (!strcmp(arg, "--source")) {
103                         rev->show_source = 1;
104                 } else if (!strcmp(arg, "-h")) {
105                         usage(builtin_log_usage);
106                 } else
107                         die("unrecognized argument: %s", arg);
108         }
110         /*
111          * defeat log.decorate configuration interacting with --pretty
112          * from the command line.
113          */
114         if (!decoration_given && rev->pretty_given)
115                 decoration_style = 0;
117         if (decoration_style) {
118                 rev->show_decorations = 1;
119                 load_ref_decorations(decoration_style);
120         }
123 /*
124  * This gives a rough estimate for how many commits we
125  * will print out in the list.
126  */
127 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
129         int n = 0;
131         while (list) {
132                 struct commit *commit = list->item;
133                 unsigned int flags = commit->object.flags;
134                 list = list->next;
135                 if (!(flags & (TREESAME | UNINTERESTING)))
136                         n++;
137         }
138         return n;
141 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
143         if (rev->shown_one) {
144                 rev->shown_one = 0;
145                 if (rev->commit_format != CMIT_FMT_ONELINE)
146                         putchar(rev->diffopt.line_termination);
147         }
148         printf("Final output: %d %s\n", nr, stage);
151 static struct itimerval early_output_timer;
153 static void log_show_early(struct rev_info *revs, struct commit_list *list)
155         int i = revs->early_output;
156         int show_header = 1;
158         sort_in_topological_order(&list, revs->lifo);
159         while (list && i) {
160                 struct commit *commit = list->item;
161                 switch (simplify_commit(revs, commit)) {
162                 case commit_show:
163                         if (show_header) {
164                                 int n = estimate_commit_count(revs, list);
165                                 show_early_header(revs, "incomplete", n);
166                                 show_header = 0;
167                         }
168                         log_tree_commit(revs, commit);
169                         i--;
170                         break;
171                 case commit_ignore:
172                         break;
173                 case commit_error:
174                         return;
175                 }
176                 list = list->next;
177         }
179         /* Did we already get enough commits for the early output? */
180         if (!i)
181                 return;
183         /*
184          * ..if no, then repeat it twice a second until we
185          * do.
186          *
187          * NOTE! We don't use "it_interval", because if the
188          * reader isn't listening, we want our output to be
189          * throttled by the writing, and not have the timer
190          * trigger every second even if we're blocked on a
191          * reader!
192          */
193         early_output_timer.it_value.tv_sec = 0;
194         early_output_timer.it_value.tv_usec = 500000;
195         setitimer(ITIMER_REAL, &early_output_timer, NULL);
198 static void early_output(int signal)
200         show_early_output = log_show_early;
203 static void setup_early_output(struct rev_info *rev)
205         struct sigaction sa;
207         /*
208          * Set up the signal handler, minimally intrusively:
209          * we only set a single volatile integer word (not
210          * using sigatomic_t - trying to avoid unnecessary
211          * system dependencies and headers), and using
212          * SA_RESTART.
213          */
214         memset(&sa, 0, sizeof(sa));
215         sa.sa_handler = early_output;
216         sigemptyset(&sa.sa_mask);
217         sa.sa_flags = SA_RESTART;
218         sigaction(SIGALRM, &sa, NULL);
220         /*
221          * If we can get the whole output in less than a
222          * tenth of a second, don't even bother doing the
223          * early-output thing..
224          *
225          * This is a one-time-only trigger.
226          */
227         early_output_timer.it_value.tv_sec = 0;
228         early_output_timer.it_value.tv_usec = 100000;
229         setitimer(ITIMER_REAL, &early_output_timer, NULL);
232 static void finish_early_output(struct rev_info *rev)
234         int n = estimate_commit_count(rev, rev->commits);
235         signal(SIGALRM, SIG_IGN);
236         show_early_header(rev, "done", n);
239 static int cmd_log_walk(struct rev_info *rev)
241         struct commit *commit;
243         if (rev->early_output)
244                 setup_early_output(rev);
246         if (prepare_revision_walk(rev))
247                 die("revision walk setup failed");
249         if (rev->early_output)
250                 finish_early_output(rev);
252         /*
253          * For --check and --exit-code, the exit code is based on CHECK_FAILED
254          * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
255          * retain that state information if replacing rev->diffopt in this loop
256          */
257         while ((commit = get_revision(rev)) != NULL) {
258                 log_tree_commit(rev, commit);
259                 if (!rev->reflog_info) {
260                         /* we allow cycles in reflog ancestry */
261                         free(commit->buffer);
262                         commit->buffer = NULL;
263                 }
264                 free_commit_list(commit->parents);
265                 commit->parents = NULL;
266         }
267         if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
268             DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
269                 return 02;
270         }
271         return diff_result_code(&rev->diffopt, 0);
274 static int git_log_config(const char *var, const char *value, void *cb)
276         if (!strcmp(var, "format.pretty"))
277                 return git_config_string(&fmt_pretty, var, value);
278         if (!strcmp(var, "format.subjectprefix"))
279                 return git_config_string(&fmt_patch_subject_prefix, var, value);
280         if (!strcmp(var, "log.date"))
281                 return git_config_string(&default_date_mode, var, value);
282         if (!strcmp(var, "log.decorate")) {
283                 decoration_style = parse_decoration_style(var, value);
284                 if (decoration_style < 0)
285                         decoration_style = 0; /* maybe warn? */
286                 return 0;
287         }
288         if (!strcmp(var, "log.showroot")) {
289                 default_show_root = git_config_bool(var, value);
290                 return 0;
291         }
292         return git_diff_ui_config(var, value, cb);
295 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
297         struct rev_info rev;
299         git_config(git_log_config, NULL);
301         if (diff_use_color_default == -1)
302                 diff_use_color_default = git_use_color_default;
304         init_revisions(&rev, prefix);
305         rev.diff = 1;
306         rev.simplify_history = 0;
307         cmd_log_init(argc, argv, prefix, &rev);
308         if (!rev.diffopt.output_format)
309                 rev.diffopt.output_format = DIFF_FORMAT_RAW;
310         return cmd_log_walk(&rev);
313 static void show_tagger(char *buf, int len, struct rev_info *rev)
315         struct strbuf out = STRBUF_INIT;
317         pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
318                 git_log_output_encoding ?
319                 git_log_output_encoding: git_commit_encoding);
320         printf("%s", out.buf);
321         strbuf_release(&out);
324 static int show_object(const unsigned char *sha1, int show_tag_object,
325         struct rev_info *rev)
327         unsigned long size;
328         enum object_type type;
329         char *buf = read_sha1_file(sha1, &type, &size);
330         int offset = 0;
332         if (!buf)
333                 return error("Could not read object %s", sha1_to_hex(sha1));
335         if (show_tag_object)
336                 while (offset < size && buf[offset] != '\n') {
337                         int new_offset = offset + 1;
338                         while (new_offset < size && buf[new_offset++] != '\n')
339                                 ; /* do nothing */
340                         if (!prefixcmp(buf + offset, "tagger "))
341                                 show_tagger(buf + offset + 7,
342                                             new_offset - offset - 7, rev);
343                         offset = new_offset;
344                 }
346         if (offset < size)
347                 fwrite(buf + offset, size - offset, 1, stdout);
348         free(buf);
349         return 0;
352 static int show_tree_object(const unsigned char *sha1,
353                 const char *base, int baselen,
354                 const char *pathname, unsigned mode, int stage, void *context)
356         printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
357         return 0;
360 int cmd_show(int argc, const char **argv, const char *prefix)
362         struct rev_info rev;
363         struct object_array_entry *objects;
364         int i, count, ret = 0;
366         git_config(git_log_config, NULL);
368         if (diff_use_color_default == -1)
369                 diff_use_color_default = git_use_color_default;
371         init_revisions(&rev, prefix);
372         rev.diff = 1;
373         rev.combine_merges = 1;
374         rev.dense_combined_merges = 1;
375         rev.always_show_header = 1;
376         rev.ignore_merges = 0;
377         rev.no_walk = 1;
378         cmd_log_init(argc, argv, prefix, &rev);
380         count = rev.pending.nr;
381         objects = rev.pending.objects;
382         for (i = 0; i < count && !ret; i++) {
383                 struct object *o = objects[i].item;
384                 const char *name = objects[i].name;
385                 switch (o->type) {
386                 case OBJ_BLOB:
387                         ret = show_object(o->sha1, 0, NULL);
388                         break;
389                 case OBJ_TAG: {
390                         struct tag *t = (struct tag *)o;
392                         if (rev.shown_one)
393                                 putchar('\n');
394                         printf("%stag %s%s\n",
395                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
396                                         t->tag,
397                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
398                         ret = show_object(o->sha1, 1, &rev);
399                         rev.shown_one = 1;
400                         if (ret)
401                                 break;
402                         o = parse_object(t->tagged->sha1);
403                         if (!o)
404                                 ret = error("Could not read object %s",
405                                             sha1_to_hex(t->tagged->sha1));
406                         objects[i].item = o;
407                         i--;
408                         break;
409                 }
410                 case OBJ_TREE:
411                         if (rev.shown_one)
412                                 putchar('\n');
413                         printf("%stree %s%s\n\n",
414                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
415                                         name,
416                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
417                         read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
418                                         show_tree_object, NULL);
419                         rev.shown_one = 1;
420                         break;
421                 case OBJ_COMMIT:
422                         rev.pending.nr = rev.pending.alloc = 0;
423                         rev.pending.objects = NULL;
424                         add_object_array(o, name, &rev.pending);
425                         ret = cmd_log_walk(&rev);
426                         break;
427                 default:
428                         ret = error("Unknown type: %d", o->type);
429                 }
430         }
431         free(objects);
432         return ret;
435 /*
436  * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
437  */
438 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
440         struct rev_info rev;
442         git_config(git_log_config, NULL);
444         if (diff_use_color_default == -1)
445                 diff_use_color_default = git_use_color_default;
447         init_revisions(&rev, prefix);
448         init_reflog_walk(&rev.reflog_info);
449         rev.abbrev_commit = 1;
450         rev.verbose_header = 1;
451         cmd_log_init(argc, argv, prefix, &rev);
453         /*
454          * This means that we override whatever commit format the user gave
455          * on the cmd line.  Sad, but cmd_log_init() currently doesn't
456          * allow us to set a different default.
457          */
458         rev.commit_format = CMIT_FMT_ONELINE;
459         rev.use_terminator = 1;
460         rev.always_show_header = 1;
462         /*
463          * We get called through "git reflog", so unlike the other log
464          * routines, we need to set up our pager manually..
465          */
466         setup_pager();
468         return cmd_log_walk(&rev);
471 int cmd_log(int argc, const char **argv, const char *prefix)
473         struct rev_info rev;
475         git_config(git_log_config, NULL);
477         if (diff_use_color_default == -1)
478                 diff_use_color_default = git_use_color_default;
480         init_revisions(&rev, prefix);
481         rev.always_show_header = 1;
482         cmd_log_init(argc, argv, prefix, &rev);
483         return cmd_log_walk(&rev);
486 /* format-patch */
488 static const char *fmt_patch_suffix = ".patch";
489 static int numbered = 0;
490 static int auto_number = 1;
492 static char *default_attach = NULL;
494 static char **extra_hdr;
495 static int extra_hdr_nr;
496 static int extra_hdr_alloc;
498 static char **extra_to;
499 static int extra_to_nr;
500 static int extra_to_alloc;
502 static char **extra_cc;
503 static int extra_cc_nr;
504 static int extra_cc_alloc;
506 static void add_header(const char *value)
508         int len = strlen(value);
509         while (len && value[len - 1] == '\n')
510                 len--;
511         if (!strncasecmp(value, "to: ", 4)) {
512                 ALLOC_GROW(extra_to, extra_to_nr + 1, extra_to_alloc);
513                 extra_to[extra_to_nr++] = xstrndup(value + 4, len - 4);
514                 return;
515         }
516         if (!strncasecmp(value, "cc: ", 4)) {
517                 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
518                 extra_cc[extra_cc_nr++] = xstrndup(value + 4, len - 4);
519                 return;
520         }
521         ALLOC_GROW(extra_hdr, extra_hdr_nr + 1, extra_hdr_alloc);
522         extra_hdr[extra_hdr_nr++] = xstrndup(value, len);
525 #define THREAD_SHALLOW 1
526 #define THREAD_DEEP 2
527 static int thread = 0;
528 static int do_signoff = 0;
530 static int git_format_config(const char *var, const char *value, void *cb)
532         if (!strcmp(var, "format.headers")) {
533                 if (!value)
534                         die("format.headers without value");
535                 add_header(value);
536                 return 0;
537         }
538         if (!strcmp(var, "format.suffix"))
539                 return git_config_string(&fmt_patch_suffix, var, value);
540         if (!strcmp(var, "format.cc")) {
541                 if (!value)
542                         return config_error_nonbool(var);
543                 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
544                 extra_cc[extra_cc_nr++] = xstrdup(value);
545                 return 0;
546         }
547         if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
548                 return 0;
549         }
550         if (!strcmp(var, "format.numbered")) {
551                 if (value && !strcasecmp(value, "auto")) {
552                         auto_number = 1;
553                         return 0;
554                 }
555                 numbered = git_config_bool(var, value);
556                 auto_number = auto_number && numbered;
557                 return 0;
558         }
559         if (!strcmp(var, "format.attach")) {
560                 if (value && *value)
561                         default_attach = xstrdup(value);
562                 else
563                         default_attach = xstrdup(git_version_string);
564                 return 0;
565         }
566         if (!strcmp(var, "format.thread")) {
567                 if (value && !strcasecmp(value, "deep")) {
568                         thread = THREAD_DEEP;
569                         return 0;
570                 }
571                 if (value && !strcasecmp(value, "shallow")) {
572                         thread = THREAD_SHALLOW;
573                         return 0;
574                 }
575                 thread = git_config_bool(var, value) && THREAD_SHALLOW;
576                 return 0;
577         }
578         if (!strcmp(var, "format.signoff")) {
579                 do_signoff = git_config_bool(var, value);
580                 return 0;
581         }
583         return git_log_config(var, value, cb);
586 static FILE *realstdout = NULL;
587 static const char *output_directory = NULL;
588 static int outdir_offset;
590 static int reopen_stdout(struct commit *commit, struct rev_info *rev)
592         struct strbuf filename = STRBUF_INIT;
593         int suffix_len = strlen(fmt_patch_suffix) + 1;
595         if (output_directory) {
596                 strbuf_addstr(&filename, output_directory);
597                 if (filename.len >=
598                     PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
599                         return error("name of output directory is too long");
600                 if (filename.buf[filename.len - 1] != '/')
601                         strbuf_addch(&filename, '/');
602         }
604         get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
606         if (!DIFF_OPT_TST(&rev->diffopt, QUICK))
607                 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
609         if (freopen(filename.buf, "w", stdout) == NULL)
610                 return error("Cannot open patch file %s", filename.buf);
612         strbuf_release(&filename);
613         return 0;
616 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
618         struct rev_info check_rev;
619         struct commit *commit;
620         struct object *o1, *o2;
621         unsigned flags1, flags2;
623         if (rev->pending.nr != 2)
624                 die("Need exactly one range.");
626         o1 = rev->pending.objects[0].item;
627         flags1 = o1->flags;
628         o2 = rev->pending.objects[1].item;
629         flags2 = o2->flags;
631         if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
632                 die("Not a range.");
634         init_patch_ids(ids);
636         /* given a range a..b get all patch ids for b..a */
637         init_revisions(&check_rev, prefix);
638         o1->flags ^= UNINTERESTING;
639         o2->flags ^= UNINTERESTING;
640         add_pending_object(&check_rev, o1, "o1");
641         add_pending_object(&check_rev, o2, "o2");
642         if (prepare_revision_walk(&check_rev))
643                 die("revision walk setup failed");
645         while ((commit = get_revision(&check_rev)) != NULL) {
646                 /* ignore merges */
647                 if (commit->parents && commit->parents->next)
648                         continue;
650                 add_commit_patch_id(commit, ids);
651         }
653         /* reset for next revision walk */
654         clear_commit_marks((struct commit *)o1,
655                         SEEN | UNINTERESTING | SHOWN | ADDED);
656         clear_commit_marks((struct commit *)o2,
657                         SEEN | UNINTERESTING | SHOWN | ADDED);
658         o1->flags = flags1;
659         o2->flags = flags2;
662 static void gen_message_id(struct rev_info *info, char *base)
664         const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
665         const char *email_start = strrchr(committer, '<');
666         const char *email_end = strrchr(committer, '>');
667         struct strbuf buf = STRBUF_INIT;
668         if (!email_start || !email_end || email_start > email_end - 1)
669                 die("Could not extract email from committer identity.");
670         strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
671                     (unsigned long) time(NULL),
672                     (int)(email_end - email_start - 1), email_start + 1);
673         info->message_id = strbuf_detach(&buf, NULL);
676 static void make_cover_letter(struct rev_info *rev, int use_stdout,
677                               int numbered, int numbered_files,
678                               struct commit *origin,
679                               int nr, struct commit **list, struct commit *head)
681         const char *committer;
682         const char *subject_start = NULL;
683         const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
684         const char *msg;
685         const char *extra_headers = rev->extra_headers;
686         struct shortlog log;
687         struct strbuf sb = STRBUF_INIT;
688         int i;
689         const char *encoding = "UTF-8";
690         struct diff_options opts;
691         int need_8bit_cte = 0;
692         struct commit *commit = NULL;
694         if (rev->commit_format != CMIT_FMT_EMAIL)
695                 die("Cover letter needs email format");
697         committer = git_committer_info(0);
699         if (!numbered_files) {
700                 /*
701                  * We fake a commit for the cover letter so we get the filename
702                  * desired.
703                  */
704                 commit = xcalloc(1, sizeof(*commit));
705                 commit->buffer = xmalloc(400);
706                 snprintf(commit->buffer, 400,
707                         "tree 0000000000000000000000000000000000000000\n"
708                         "parent %s\n"
709                         "author %s\n"
710                         "committer %s\n\n"
711                         "cover letter\n",
712                         sha1_to_hex(head->object.sha1), committer, committer);
713         }
715         if (!use_stdout && reopen_stdout(commit, rev))
716                 return;
718         if (commit) {
720                 free(commit->buffer);
721                 free(commit);
722         }
724         log_write_email_headers(rev, head, &subject_start, &extra_headers,
725                                 &need_8bit_cte);
727         for (i = 0; !need_8bit_cte && i < nr; i++)
728                 if (has_non_ascii(list[i]->buffer))
729                         need_8bit_cte = 1;
731         msg = body;
732         pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
733                      encoding);
734         pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
735                       encoding, need_8bit_cte);
736         pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
737         printf("%s\n", sb.buf);
739         strbuf_release(&sb);
741         shortlog_init(&log);
742         log.wrap_lines = 1;
743         log.wrap = 72;
744         log.in1 = 2;
745         log.in2 = 4;
746         for (i = 0; i < nr; i++)
747                 shortlog_add_commit(&log, list[i]);
749         shortlog_output(&log);
751         /*
752          * We can only do diffstat with a unique reference point
753          */
754         if (!origin)
755                 return;
757         memcpy(&opts, &rev->diffopt, sizeof(opts));
758         opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
760         diff_setup_done(&opts);
762         diff_tree_sha1(origin->tree->object.sha1,
763                        head->tree->object.sha1,
764                        "", &opts);
765         diffcore_std(&opts);
766         diff_flush(&opts);
768         printf("\n");
771 static const char *clean_message_id(const char *msg_id)
773         char ch;
774         const char *a, *z, *m;
776         m = msg_id;
777         while ((ch = *m) && (isspace(ch) || (ch == '<')))
778                 m++;
779         a = m;
780         z = NULL;
781         while ((ch = *m)) {
782                 if (!isspace(ch) && (ch != '>'))
783                         z = m;
784                 m++;
785         }
786         if (!z)
787                 die("insane in-reply-to: %s", msg_id);
788         if (++z == m)
789                 return a;
790         return xmemdupz(a, z - a);
793 static const char *set_outdir(const char *prefix, const char *output_directory)
795         if (output_directory && is_absolute_path(output_directory))
796                 return output_directory;
798         if (!prefix || !*prefix) {
799                 if (output_directory)
800                         return output_directory;
801                 /* The user did not explicitly ask for "./" */
802                 outdir_offset = 2;
803                 return "./";
804         }
806         outdir_offset = strlen(prefix);
807         if (!output_directory)
808                 return prefix;
810         return xstrdup(prefix_filename(prefix, outdir_offset,
811                                        output_directory));
814 static const char * const builtin_format_patch_usage[] = {
815         "git format-patch [options] [<since> | <revision range>]",
816         NULL
817 };
819 static int keep_subject = 0;
821 static int keep_callback(const struct option *opt, const char *arg, int unset)
823         ((struct rev_info *)opt->value)->total = -1;
824         keep_subject = 1;
825         return 0;
828 static int subject_prefix = 0;
830 static int subject_prefix_callback(const struct option *opt, const char *arg,
831                             int unset)
833         subject_prefix = 1;
834         ((struct rev_info *)opt->value)->subject_prefix = arg;
835         return 0;
838 static int numbered_cmdline_opt = 0;
840 static int numbered_callback(const struct option *opt, const char *arg,
841                              int unset)
843         *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
844         if (unset)
845                 auto_number =  0;
846         return 0;
849 static int no_numbered_callback(const struct option *opt, const char *arg,
850                                 int unset)
852         return numbered_callback(opt, arg, 1);
855 static int output_directory_callback(const struct option *opt, const char *arg,
856                               int unset)
858         const char **dir = (const char **)opt->value;
859         if (*dir)
860                 die("Two output directories?");
861         *dir = arg;
862         return 0;
865 static int thread_callback(const struct option *opt, const char *arg, int unset)
867         int *thread = (int *)opt->value;
868         if (unset)
869                 *thread = 0;
870         else if (!arg || !strcmp(arg, "shallow"))
871                 *thread = THREAD_SHALLOW;
872         else if (!strcmp(arg, "deep"))
873                 *thread = THREAD_DEEP;
874         else
875                 return 1;
876         return 0;
879 static int attach_callback(const struct option *opt, const char *arg, int unset)
881         struct rev_info *rev = (struct rev_info *)opt->value;
882         if (unset)
883                 rev->mime_boundary = NULL;
884         else if (arg)
885                 rev->mime_boundary = arg;
886         else
887                 rev->mime_boundary = git_version_string;
888         rev->no_inline = unset ? 0 : 1;
889         return 0;
892 static int inline_callback(const struct option *opt, const char *arg, int unset)
894         struct rev_info *rev = (struct rev_info *)opt->value;
895         if (unset)
896                 rev->mime_boundary = NULL;
897         else if (arg)
898                 rev->mime_boundary = arg;
899         else
900                 rev->mime_boundary = git_version_string;
901         rev->no_inline = 0;
902         return 0;
905 static int header_callback(const struct option *opt, const char *arg, int unset)
907         add_header(arg);
908         return 0;
911 static int cc_callback(const struct option *opt, const char *arg, int unset)
913         ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
914         extra_cc[extra_cc_nr++] = xstrdup(arg);
915         return 0;
918 int cmd_format_patch(int argc, const char **argv, const char *prefix)
920         struct commit *commit;
921         struct commit **list = NULL;
922         struct rev_info rev;
923         int nr = 0, total, i;
924         int use_stdout = 0;
925         int start_number = -1;
926         int numbered_files = 0;         /* _just_ numbers */
927         int ignore_if_in_upstream = 0;
928         int cover_letter = 0;
929         int boundary_count = 0;
930         int no_binary_diff = 0;
931         struct commit *origin = NULL, *head = NULL;
932         const char *in_reply_to = NULL;
933         struct patch_ids ids;
934         char *add_signoff = NULL;
935         struct strbuf buf = STRBUF_INIT;
936         int use_patch_format = 0;
937         const struct option builtin_format_patch_options[] = {
938                 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
939                             "use [PATCH n/m] even with a single patch",
940                             PARSE_OPT_NOARG, numbered_callback },
941                 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
942                             "use [PATCH] even with multiple patches",
943                             PARSE_OPT_NOARG, no_numbered_callback },
944                 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
945                 OPT_BOOLEAN(0, "stdout", &use_stdout,
946                             "print patches to standard out"),
947                 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
948                             "generate a cover letter"),
949                 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
950                             "use simple number sequence for output file names"),
951                 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
952                             "use <sfx> instead of '.patch'"),
953                 OPT_INTEGER(0, "start-number", &start_number,
954                             "start numbering patches at <n> instead of 1"),
955                 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
956                             "Use [<prefix>] instead of [PATCH]",
957                             PARSE_OPT_NONEG, subject_prefix_callback },
958                 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
959                             "dir", "store resulting files in <dir>",
960                             PARSE_OPT_NONEG, output_directory_callback },
961                 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
962                             "don't strip/add [PATCH]",
963                             PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
964                 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
965                             "don't output binary diffs"),
966                 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
967                             "don't include a patch matching a commit upstream"),
968                 { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
969                   "show patch format instead of default (patch + stat)",
970                   PARSE_OPT_NONEG | PARSE_OPT_NOARG },
971                 OPT_GROUP("Messaging"),
972                 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
973                             "add email header", PARSE_OPT_NONEG,
974                             header_callback },
975                 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
976                             PARSE_OPT_NONEG, cc_callback },
977                 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
978                             "make first mail a reply to <message-id>"),
979                 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
980                             "attach the patch", PARSE_OPT_OPTARG,
981                             attach_callback },
982                 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
983                             "inline the patch",
984                             PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
985                             inline_callback },
986                 { OPTION_CALLBACK, 0, "thread", &thread, "style",
987                             "enable message threading, styles: shallow, deep",
988                             PARSE_OPT_OPTARG, thread_callback },
989                 OPT_END()
990         };
992         git_config(git_format_config, NULL);
993         init_revisions(&rev, prefix);
994         rev.commit_format = CMIT_FMT_EMAIL;
995         rev.verbose_header = 1;
996         rev.diff = 1;
997         rev.combine_merges = 0;
998         rev.ignore_merges = 1;
999         DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1001         rev.subject_prefix = fmt_patch_subject_prefix;
1003         if (default_attach) {
1004                 rev.mime_boundary = default_attach;
1005                 rev.no_inline = 1;
1006         }
1008         /*
1009          * Parse the arguments before setup_revisions(), or something
1010          * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1011          * possibly a valid SHA1.
1012          */
1013         argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1014                              builtin_format_patch_usage,
1015                              PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1016                              PARSE_OPT_KEEP_DASHDASH);
1018         if (do_signoff) {
1019                 const char *committer;
1020                 const char *endpos;
1021                 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
1022                 endpos = strchr(committer, '>');
1023                 if (!endpos)
1024                         die("bogus committer info %s", committer);
1025                 add_signoff = xmemdupz(committer, endpos - committer + 1);
1026         }
1028         for (i = 0; i < extra_hdr_nr; i++) {
1029                 strbuf_addstr(&buf, extra_hdr[i]);
1030                 strbuf_addch(&buf, '\n');
1031         }
1033         if (extra_to_nr)
1034                 strbuf_addstr(&buf, "To: ");
1035         for (i = 0; i < extra_to_nr; i++) {
1036                 if (i)
1037                         strbuf_addstr(&buf, "    ");
1038                 strbuf_addstr(&buf, extra_to[i]);
1039                 if (i + 1 < extra_to_nr)
1040                         strbuf_addch(&buf, ',');
1041                 strbuf_addch(&buf, '\n');
1042         }
1044         if (extra_cc_nr)
1045                 strbuf_addstr(&buf, "Cc: ");
1046         for (i = 0; i < extra_cc_nr; i++) {
1047                 if (i)
1048                         strbuf_addstr(&buf, "    ");
1049                 strbuf_addstr(&buf, extra_cc[i]);
1050                 if (i + 1 < extra_cc_nr)
1051                         strbuf_addch(&buf, ',');
1052                 strbuf_addch(&buf, '\n');
1053         }
1055         rev.extra_headers = strbuf_detach(&buf, NULL);
1057         if (start_number < 0)
1058                 start_number = 1;
1060         /*
1061          * If numbered is set solely due to format.numbered in config,
1062          * and it would conflict with --keep-subject (-k) from the
1063          * command line, reset "numbered".
1064          */
1065         if (numbered && keep_subject && !numbered_cmdline_opt)
1066                 numbered = 0;
1068         if (numbered && keep_subject)
1069                 die ("-n and -k are mutually exclusive.");
1070         if (keep_subject && subject_prefix)
1071                 die ("--subject-prefix and -k are mutually exclusive.");
1073         argc = setup_revisions(argc, argv, &rev, "HEAD");
1074         if (argc > 1)
1075                 die ("unrecognized argument: %s", argv[1]);
1077         if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1078                 die("--name-only does not make sense");
1079         if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1080                 die("--name-status does not make sense");
1081         if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1082                 die("--check does not make sense");
1084         if (!use_patch_format &&
1085                 (!rev.diffopt.output_format ||
1086                  rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1087                 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1089         /* Always generate a patch */
1090         rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1092         if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1093                 DIFF_OPT_SET(&rev.diffopt, BINARY);
1095         if (!use_stdout)
1096                 output_directory = set_outdir(prefix, output_directory);
1098         if (output_directory) {
1099                 if (use_stdout)
1100                         die("standard output, or directory, which one?");
1101                 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1102                         die_errno("Could not create directory '%s'",
1103                                   output_directory);
1104         }
1106         if (rev.pending.nr == 1) {
1107                 if (rev.max_count < 0 && !rev.show_root_diff) {
1108                         /*
1109                          * This is traditional behaviour of "git format-patch
1110                          * origin" that prepares what the origin side still
1111                          * does not have.
1112                          */
1113                         rev.pending.objects[0].item->flags |= UNINTERESTING;
1114                         add_head_to_pending(&rev);
1115                 }
1116                 /*
1117                  * Otherwise, it is "format-patch -22 HEAD", and/or
1118                  * "format-patch --root HEAD".  The user wants
1119                  * get_revision() to do the usual traversal.
1120                  */
1121         }
1123         /*
1124          * We cannot move this anywhere earlier because we do want to
1125          * know if --root was given explicitly from the comand line.
1126          */
1127         rev.show_root_diff = 1;
1129         if (cover_letter) {
1130                 /* remember the range */
1131                 int i;
1132                 for (i = 0; i < rev.pending.nr; i++) {
1133                         struct object *o = rev.pending.objects[i].item;
1134                         if (!(o->flags & UNINTERESTING))
1135                                 head = (struct commit *)o;
1136                 }
1137                 /* We can't generate a cover letter without any patches */
1138                 if (!head)
1139                         return 0;
1140         }
1142         if (ignore_if_in_upstream)
1143                 get_patch_ids(&rev, &ids, prefix);
1145         if (!use_stdout)
1146                 realstdout = xfdopen(xdup(1), "w");
1148         if (prepare_revision_walk(&rev))
1149                 die("revision walk setup failed");
1150         rev.boundary = 1;
1151         while ((commit = get_revision(&rev)) != NULL) {
1152                 if (commit->object.flags & BOUNDARY) {
1153                         boundary_count++;
1154                         origin = (boundary_count == 1) ? commit : NULL;
1155                         continue;
1156                 }
1158                 /* ignore merges */
1159                 if (commit->parents && commit->parents->next)
1160                         continue;
1162                 if (ignore_if_in_upstream &&
1163                                 has_commit_patch_id(commit, &ids))
1164                         continue;
1166                 nr++;
1167                 list = xrealloc(list, nr * sizeof(list[0]));
1168                 list[nr - 1] = commit;
1169         }
1170         total = nr;
1171         if (!keep_subject && auto_number && total > 1)
1172                 numbered = 1;
1173         if (numbered)
1174                 rev.total = total + start_number - 1;
1175         if (in_reply_to || thread || cover_letter)
1176                 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1177         if (in_reply_to) {
1178                 const char *msgid = clean_message_id(in_reply_to);
1179                 string_list_append(msgid, rev.ref_message_ids);
1180         }
1181         rev.numbered_files = numbered_files;
1182         rev.patch_suffix = fmt_patch_suffix;
1183         if (cover_letter) {
1184                 if (thread)
1185                         gen_message_id(&rev, "cover");
1186                 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1187                                   origin, nr, list, head);
1188                 total++;
1189                 start_number--;
1190         }
1191         rev.add_signoff = add_signoff;
1192         while (0 <= --nr) {
1193                 int shown;
1194                 commit = list[nr];
1195                 rev.nr = total - nr + (start_number - 1);
1196                 /* Make the second and subsequent mails replies to the first */
1197                 if (thread) {
1198                         /* Have we already had a message ID? */
1199                         if (rev.message_id) {
1200                                 /*
1201                                  * For deep threading: make every mail
1202                                  * a reply to the previous one, no
1203                                  * matter what other options are set.
1204                                  *
1205                                  * For shallow threading:
1206                                  *
1207                                  * Without --cover-letter and
1208                                  * --in-reply-to, make every mail a
1209                                  * reply to the one before.
1210                                  *
1211                                  * With --in-reply-to but no
1212                                  * --cover-letter, make every mail a
1213                                  * reply to the <reply-to>.
1214                                  *
1215                                  * With --cover-letter, make every
1216                                  * mail but the cover letter a reply
1217                                  * to the cover letter.  The cover
1218                                  * letter is a reply to the
1219                                  * --in-reply-to, if specified.
1220                                  */
1221                                 if (thread == THREAD_SHALLOW
1222                                     && rev.ref_message_ids->nr > 0
1223                                     && (!cover_letter || rev.nr > 1))
1224                                         free(rev.message_id);
1225                                 else
1226                                         string_list_append(rev.message_id,
1227                                                            rev.ref_message_ids);
1228                         }
1229                         gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1230                 }
1232                 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1233                                                  &rev))
1234                         die("Failed to create output files");
1235                 shown = log_tree_commit(&rev, commit);
1236                 free(commit->buffer);
1237                 commit->buffer = NULL;
1239                 /* We put one extra blank line between formatted
1240                  * patches and this flag is used by log-tree code
1241                  * to see if it needs to emit a LF before showing
1242                  * the log; when using one file per patch, we do
1243                  * not want the extra blank line.
1244                  */
1245                 if (!use_stdout)
1246                         rev.shown_one = 0;
1247                 if (shown) {
1248                         if (rev.mime_boundary)
1249                                 printf("\n--%s%s--\n\n\n",
1250                                        mime_boundary_leader,
1251                                        rev.mime_boundary);
1252                         else
1253                                 printf("-- \n%s\n\n", git_version_string);
1254                 }
1255                 if (!use_stdout)
1256                         fclose(stdout);
1257         }
1258         free(list);
1259         if (ignore_if_in_upstream)
1260                 free_patch_ids(&ids);
1261         return 0;
1264 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1266         unsigned char sha1[20];
1267         if (get_sha1(arg, sha1) == 0) {
1268                 struct commit *commit = lookup_commit_reference(sha1);
1269                 if (commit) {
1270                         commit->object.flags |= flags;
1271                         add_pending_object(revs, &commit->object, arg);
1272                         return 0;
1273                 }
1274         }
1275         return -1;
1278 static const char cherry_usage[] =
1279 "git cherry [-v] [<upstream> [<head> [<limit>]]]";
1280 int cmd_cherry(int argc, const char **argv, const char *prefix)
1282         struct rev_info revs;
1283         struct patch_ids ids;
1284         struct commit *commit;
1285         struct commit_list *list = NULL;
1286         struct branch *current_branch;
1287         const char *upstream;
1288         const char *head = "HEAD";
1289         const char *limit = NULL;
1290         int verbose = 0;
1292         if (argc > 1 && !strcmp(argv[1], "-v")) {
1293                 verbose = 1;
1294                 argc--;
1295                 argv++;
1296         }
1298         if (argc > 1 && !strcmp(argv[1], "-h"))
1299                 usage(cherry_usage);
1301         switch (argc) {
1302         case 4:
1303                 limit = argv[3];
1304                 /* FALLTHROUGH */
1305         case 3:
1306                 head = argv[2];
1307                 /* FALLTHROUGH */
1308         case 2:
1309                 upstream = argv[1];
1310                 break;
1311         default:
1312                 current_branch = branch_get(NULL);
1313                 if (!current_branch || !current_branch->merge
1314                                         || !current_branch->merge[0]
1315                                         || !current_branch->merge[0]->dst) {
1316                         fprintf(stderr, "Could not find a tracked"
1317                                         " remote branch, please"
1318                                         " specify <upstream> manually.\n");
1319                         usage(cherry_usage);
1320                 }
1322                 upstream = current_branch->merge[0]->dst;
1323         }
1325         init_revisions(&revs, prefix);
1326         revs.diff = 1;
1327         revs.combine_merges = 0;
1328         revs.ignore_merges = 1;
1329         DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1331         if (add_pending_commit(head, &revs, 0))
1332                 die("Unknown commit %s", head);
1333         if (add_pending_commit(upstream, &revs, UNINTERESTING))
1334                 die("Unknown commit %s", upstream);
1336         /* Don't say anything if head and upstream are the same. */
1337         if (revs.pending.nr == 2) {
1338                 struct object_array_entry *o = revs.pending.objects;
1339                 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1340                         return 0;
1341         }
1343         get_patch_ids(&revs, &ids, prefix);
1345         if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1346                 die("Unknown commit %s", limit);
1348         /* reverse the list of commits */
1349         if (prepare_revision_walk(&revs))
1350                 die("revision walk setup failed");
1351         while ((commit = get_revision(&revs)) != NULL) {
1352                 /* ignore merges */
1353                 if (commit->parents && commit->parents->next)
1354                         continue;
1356                 commit_list_insert(commit, &list);
1357         }
1359         while (list) {
1360                 char sign = '+';
1362                 commit = list->item;
1363                 if (has_commit_patch_id(commit, &ids))
1364                         sign = '-';
1366                 if (verbose) {
1367                         struct strbuf buf = STRBUF_INIT;
1368                         struct pretty_print_context ctx = {0};
1369                         pretty_print_commit(CMIT_FMT_ONELINE, commit,
1370                                             &buf, &ctx);
1371                         printf("%c %s %s\n", sign,
1372                                sha1_to_hex(commit->object.sha1), buf.buf);
1373                         strbuf_release(&buf);
1374                 }
1375                 else {
1376                         printf("%c %s\n", sign,
1377                                sha1_to_hex(commit->object.sha1));
1378                 }
1380                 list = list->next;
1381         }
1383         free_patch_ids(&ids);
1384         return 0;