Code

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