Code

Merge branch 'gp/bisect-fix'
[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 "refs.h"
18 #include "run-command.h"
19 #include "shortlog.h"
21 static int default_show_root = 1;
22 static const char *fmt_patch_subject_prefix = "PATCH";
23 static const char *fmt_pretty;
25 static void add_name_decoration(const char *prefix, const char *name, struct object *obj)
26 {
27         int plen = strlen(prefix);
28         int nlen = strlen(name);
29         struct name_decoration *res = xmalloc(sizeof(struct name_decoration) + plen + nlen);
30         memcpy(res->name, prefix, plen);
31         memcpy(res->name + plen, name, nlen + 1);
32         res->next = add_decoration(&name_decoration, obj, res);
33 }
35 static int add_ref_decoration(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
36 {
37         struct object *obj = parse_object(sha1);
38         if (!obj)
39                 return 0;
40         add_name_decoration("", refname, obj);
41         while (obj->type == OBJ_TAG) {
42                 obj = ((struct tag *)obj)->tagged;
43                 if (!obj)
44                         break;
45                 add_name_decoration("tag: ", refname, obj);
46         }
47         return 0;
48 }
50 static void cmd_log_init(int argc, const char **argv, const char *prefix,
51                       struct rev_info *rev)
52 {
53         int i;
54         int decorate = 0;
56         rev->abbrev = DEFAULT_ABBREV;
57         rev->commit_format = CMIT_FMT_DEFAULT;
58         if (fmt_pretty)
59                 get_commit_format(fmt_pretty, rev);
60         rev->verbose_header = 1;
61         DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
62         rev->show_root_diff = default_show_root;
63         rev->subject_prefix = fmt_patch_subject_prefix;
64         argc = setup_revisions(argc, argv, rev, "HEAD");
65         if (rev->diffopt.pickaxe || rev->diffopt.filter)
66                 rev->always_show_header = 0;
67         if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
68                 rev->always_show_header = 0;
69                 if (rev->diffopt.nr_paths != 1)
70                         usage("git logs can only follow renames on one pathname at a time");
71         }
72         for (i = 1; i < argc; i++) {
73                 const char *arg = argv[i];
74                 if (!strcmp(arg, "--decorate")) {
75                         if (!decorate)
76                                 for_each_ref(add_ref_decoration, NULL);
77                         decorate = 1;
78                 } else
79                         die("unrecognized argument: %s", arg);
80         }
81 }
83 /*
84  * This gives a rough estimate for how many commits we
85  * will print out in the list.
86  */
87 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
88 {
89         int n = 0;
91         while (list) {
92                 struct commit *commit = list->item;
93                 unsigned int flags = commit->object.flags;
94                 list = list->next;
95                 if (!(flags & (TREESAME | UNINTERESTING)))
96                         n++;
97         }
98         return n;
99 }
101 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
103         if (rev->shown_one) {
104                 rev->shown_one = 0;
105                 if (rev->commit_format != CMIT_FMT_ONELINE)
106                         putchar(rev->diffopt.line_termination);
107         }
108         printf("Final output: %d %s\n", nr, stage);
111 struct itimerval early_output_timer;
113 static void log_show_early(struct rev_info *revs, struct commit_list *list)
115         int i = revs->early_output;
116         int show_header = 1;
118         sort_in_topological_order(&list, revs->lifo);
119         while (list && i) {
120                 struct commit *commit = list->item;
121                 switch (simplify_commit(revs, commit)) {
122                 case commit_show:
123                         if (show_header) {
124                                 int n = estimate_commit_count(revs, list);
125                                 show_early_header(revs, "incomplete", n);
126                                 show_header = 0;
127                         }
128                         log_tree_commit(revs, commit);
129                         i--;
130                         break;
131                 case commit_ignore:
132                         break;
133                 case commit_error:
134                         return;
135                 }
136                 list = list->next;
137         }
139         /* Did we already get enough commits for the early output? */
140         if (!i)
141                 return;
143         /*
144          * ..if no, then repeat it twice a second until we
145          * do.
146          *
147          * NOTE! We don't use "it_interval", because if the
148          * reader isn't listening, we want our output to be
149          * throttled by the writing, and not have the timer
150          * trigger every second even if we're blocked on a
151          * reader!
152          */
153         early_output_timer.it_value.tv_sec = 0;
154         early_output_timer.it_value.tv_usec = 500000;
155         setitimer(ITIMER_REAL, &early_output_timer, NULL);
158 static void early_output(int signal)
160         show_early_output = log_show_early;
163 static void setup_early_output(struct rev_info *rev)
165         struct sigaction sa;
167         /*
168          * Set up the signal handler, minimally intrusively:
169          * we only set a single volatile integer word (not
170          * using sigatomic_t - trying to avoid unnecessary
171          * system dependencies and headers), and using
172          * SA_RESTART.
173          */
174         memset(&sa, 0, sizeof(sa));
175         sa.sa_handler = early_output;
176         sigemptyset(&sa.sa_mask);
177         sa.sa_flags = SA_RESTART;
178         sigaction(SIGALRM, &sa, NULL);
180         /*
181          * If we can get the whole output in less than a
182          * tenth of a second, don't even bother doing the
183          * early-output thing..
184          *
185          * This is a one-time-only trigger.
186          */
187         early_output_timer.it_value.tv_sec = 0;
188         early_output_timer.it_value.tv_usec = 100000;
189         setitimer(ITIMER_REAL, &early_output_timer, NULL);
192 static void finish_early_output(struct rev_info *rev)
194         int n = estimate_commit_count(rev, rev->commits);
195         signal(SIGALRM, SIG_IGN);
196         show_early_header(rev, "done", n);
199 static int cmd_log_walk(struct rev_info *rev)
201         struct commit *commit;
203         if (rev->early_output)
204                 setup_early_output(rev);
206         if (prepare_revision_walk(rev))
207                 die("revision walk setup failed");
209         if (rev->early_output)
210                 finish_early_output(rev);
212         while ((commit = get_revision(rev)) != NULL) {
213                 log_tree_commit(rev, commit);
214                 if (!rev->reflog_info) {
215                         /* we allow cycles in reflog ancestry */
216                         free(commit->buffer);
217                         commit->buffer = NULL;
218                 }
219                 free_commit_list(commit->parents);
220                 commit->parents = NULL;
221         }
222         return 0;
225 static int git_log_config(const char *var, const char *value)
227         if (!strcmp(var, "format.pretty"))
228                 return git_config_string(&fmt_pretty, var, value);
229         if (!strcmp(var, "format.subjectprefix")) {
230                 if (!value)
231                         config_error_nonbool(var);
232                 fmt_patch_subject_prefix = xstrdup(value);
233                 return 0;
234         }
235         if (!strcmp(var, "log.showroot")) {
236                 default_show_root = git_config_bool(var, value);
237                 return 0;
238         }
239         return git_diff_ui_config(var, value);
242 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
244         struct rev_info rev;
246         git_config(git_log_config);
248         if (diff_use_color_default == -1)
249                 diff_use_color_default = git_use_color_default;
251         init_revisions(&rev, prefix);
252         rev.diff = 1;
253         rev.simplify_history = 0;
254         cmd_log_init(argc, argv, prefix, &rev);
255         if (!rev.diffopt.output_format)
256                 rev.diffopt.output_format = DIFF_FORMAT_RAW;
257         return cmd_log_walk(&rev);
260 static void show_tagger(char *buf, int len, struct rev_info *rev)
262         char *email_end, *p;
263         unsigned long date;
264         int tz;
266         email_end = memchr(buf, '>', len);
267         if (!email_end)
268                 return;
269         p = ++email_end;
270         while (isspace(*p))
271                 p++;
272         date = strtoul(p, &p, 10);
273         while (isspace(*p))
274                 p++;
275         tz = (int)strtol(p, NULL, 10);
276         printf("Tagger: %.*s\nDate:   %s\n", (int)(email_end - buf), buf,
277                show_date(date, tz, rev->date_mode));
280 static int show_object(const unsigned char *sha1, int show_tag_object,
281         struct rev_info *rev)
283         unsigned long size;
284         enum object_type type;
285         char *buf = read_sha1_file(sha1, &type, &size);
286         int offset = 0;
288         if (!buf)
289                 return error("Could not read object %s", sha1_to_hex(sha1));
291         if (show_tag_object)
292                 while (offset < size && buf[offset] != '\n') {
293                         int new_offset = offset + 1;
294                         while (new_offset < size && buf[new_offset++] != '\n')
295                                 ; /* do nothing */
296                         if (!prefixcmp(buf + offset, "tagger "))
297                                 show_tagger(buf + offset + 7,
298                                             new_offset - offset - 7, rev);
299                         offset = new_offset;
300                 }
302         if (offset < size)
303                 fwrite(buf + offset, size - offset, 1, stdout);
304         free(buf);
305         return 0;
308 static int show_tree_object(const unsigned char *sha1,
309                 const char *base, int baselen,
310                 const char *pathname, unsigned mode, int stage)
312         printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
313         return 0;
316 int cmd_show(int argc, const char **argv, const char *prefix)
318         struct rev_info rev;
319         struct object_array_entry *objects;
320         int i, count, ret = 0;
322         git_config(git_log_config);
324         if (diff_use_color_default == -1)
325                 diff_use_color_default = git_use_color_default;
327         init_revisions(&rev, prefix);
328         rev.diff = 1;
329         rev.combine_merges = 1;
330         rev.dense_combined_merges = 1;
331         rev.always_show_header = 1;
332         rev.ignore_merges = 0;
333         rev.no_walk = 1;
334         cmd_log_init(argc, argv, prefix, &rev);
336         count = rev.pending.nr;
337         objects = rev.pending.objects;
338         for (i = 0; i < count && !ret; i++) {
339                 struct object *o = objects[i].item;
340                 const char *name = objects[i].name;
341                 switch (o->type) {
342                 case OBJ_BLOB:
343                         ret = show_object(o->sha1, 0, NULL);
344                         break;
345                 case OBJ_TAG: {
346                         struct tag *t = (struct tag *)o;
348                         printf("%stag %s%s\n",
349                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
350                                         t->tag,
351                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
352                         ret = show_object(o->sha1, 1, &rev);
353                         objects[i].item = (struct object *)t->tagged;
354                         i--;
355                         break;
356                 }
357                 case OBJ_TREE:
358                         printf("%stree %s%s\n\n",
359                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
360                                         name,
361                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
362                         read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
363                                         show_tree_object);
364                         break;
365                 case OBJ_COMMIT:
366                         rev.pending.nr = rev.pending.alloc = 0;
367                         rev.pending.objects = NULL;
368                         add_object_array(o, name, &rev.pending);
369                         ret = cmd_log_walk(&rev);
370                         break;
371                 default:
372                         ret = error("Unknown type: %d", o->type);
373                 }
374         }
375         free(objects);
376         return ret;
379 /*
380  * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
381  */
382 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
384         struct rev_info rev;
386         git_config(git_log_config);
388         if (diff_use_color_default == -1)
389                 diff_use_color_default = git_use_color_default;
391         init_revisions(&rev, prefix);
392         init_reflog_walk(&rev.reflog_info);
393         rev.abbrev_commit = 1;
394         rev.verbose_header = 1;
395         cmd_log_init(argc, argv, prefix, &rev);
397         /*
398          * This means that we override whatever commit format the user gave
399          * on the cmd line.  Sad, but cmd_log_init() currently doesn't
400          * allow us to set a different default.
401          */
402         rev.commit_format = CMIT_FMT_ONELINE;
403         rev.use_terminator = 1;
404         rev.always_show_header = 1;
406         /*
407          * We get called through "git reflog", so unlike the other log
408          * routines, we need to set up our pager manually..
409          */
410         setup_pager();
412         return cmd_log_walk(&rev);
415 int cmd_log(int argc, const char **argv, const char *prefix)
417         struct rev_info rev;
419         git_config(git_log_config);
421         if (diff_use_color_default == -1)
422                 diff_use_color_default = git_use_color_default;
424         init_revisions(&rev, prefix);
425         rev.always_show_header = 1;
426         cmd_log_init(argc, argv, prefix, &rev);
427         return cmd_log_walk(&rev);
430 /* format-patch */
431 #define FORMAT_PATCH_NAME_MAX 64
433 static int istitlechar(char c)
435         return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
436                 (c >= '0' && c <= '9') || c == '.' || c == '_';
439 static const char *fmt_patch_suffix = ".patch";
440 static int numbered = 0;
441 static int auto_number = 0;
443 static char **extra_hdr;
444 static int extra_hdr_nr;
445 static int extra_hdr_alloc;
447 static char **extra_to;
448 static int extra_to_nr;
449 static int extra_to_alloc;
451 static char **extra_cc;
452 static int extra_cc_nr;
453 static int extra_cc_alloc;
455 static void add_header(const char *value)
457         int len = strlen(value);
458         while (value[len - 1] == '\n')
459                 len--;
460         if (!strncasecmp(value, "to: ", 4)) {
461                 ALLOC_GROW(extra_to, extra_to_nr + 1, extra_to_alloc);
462                 extra_to[extra_to_nr++] = xstrndup(value + 4, len - 4);
463                 return;
464         }
465         if (!strncasecmp(value, "cc: ", 4)) {
466                 ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
467                 extra_cc[extra_cc_nr++] = xstrndup(value + 4, len - 4);
468                 return;
469         }
470         ALLOC_GROW(extra_hdr, extra_hdr_nr + 1, extra_hdr_alloc);
471         extra_hdr[extra_hdr_nr++] = xstrndup(value, len);
474 static int git_format_config(const char *var, const char *value)
476         if (!strcmp(var, "format.headers")) {
477                 if (!value)
478                         die("format.headers without value");
479                 add_header(value);
480                 return 0;
481         }
482         if (!strcmp(var, "format.suffix")) {
483                 if (!value)
484                         return config_error_nonbool(var);
485                 fmt_patch_suffix = xstrdup(value);
486                 return 0;
487         }
488         if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
489                 return 0;
490         }
491         if (!strcmp(var, "format.numbered")) {
492                 if (value && !strcasecmp(value, "auto")) {
493                         auto_number = 1;
494                         return 0;
495                 }
496                 numbered = git_config_bool(var, value);
497                 return 0;
498         }
500         return git_log_config(var, value);
504 static const char *get_oneline_for_filename(struct commit *commit,
505                                             int keep_subject)
507         static char filename[PATH_MAX];
508         char *sol;
509         int len = 0;
510         int suffix_len = strlen(fmt_patch_suffix) + 1;
512         sol = strstr(commit->buffer, "\n\n");
513         if (!sol)
514                 filename[0] = '\0';
515         else {
516                 int j, space = 0;
518                 sol += 2;
519                 /* strip [PATCH] or [PATCH blabla] */
520                 if (!keep_subject && !prefixcmp(sol, "[PATCH")) {
521                         char *eos = strchr(sol + 6, ']');
522                         if (eos) {
523                                 while (isspace(*eos))
524                                         eos++;
525                                 sol = eos;
526                         }
527                 }
529                 for (j = 0;
530                      j < FORMAT_PATCH_NAME_MAX - suffix_len - 5 &&
531                              len < sizeof(filename) - suffix_len &&
532                              sol[j] && sol[j] != '\n';
533                      j++) {
534                         if (istitlechar(sol[j])) {
535                                 if (space) {
536                                         filename[len++] = '-';
537                                         space = 0;
538                                 }
539                                 filename[len++] = sol[j];
540                                 if (sol[j] == '.')
541                                         while (sol[j + 1] == '.')
542                                                 j++;
543                         } else
544                                 space = 1;
545                 }
546                 while (filename[len - 1] == '.'
547                        || filename[len - 1] == '-')
548                         len--;
549                 filename[len] = '\0';
550         }
551         return filename;
554 static FILE *realstdout = NULL;
555 static const char *output_directory = NULL;
557 static int reopen_stdout(const char *oneline, int nr, int total)
559         char filename[PATH_MAX];
560         int len = 0;
561         int suffix_len = strlen(fmt_patch_suffix) + 1;
563         if (output_directory) {
564                 len = snprintf(filename, sizeof(filename), "%s",
565                                 output_directory);
566                 if (len >=
567                     sizeof(filename) - FORMAT_PATCH_NAME_MAX - suffix_len)
568                         return error("name of output directory is too long");
569                 if (filename[len - 1] != '/')
570                         filename[len++] = '/';
571         }
573         if (!oneline)
574                 len += sprintf(filename + len, "%d", nr);
575         else {
576                 len += sprintf(filename + len, "%04d-", nr);
577                 len += snprintf(filename + len, sizeof(filename) - len - 1
578                                 - suffix_len, "%s", oneline);
579                 strcpy(filename + len, fmt_patch_suffix);
580         }
582         fprintf(realstdout, "%s\n", filename);
583         if (freopen(filename, "w", stdout) == NULL)
584                 return error("Cannot open patch file %s",filename);
586         return 0;
589 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
591         struct rev_info check_rev;
592         struct commit *commit;
593         struct object *o1, *o2;
594         unsigned flags1, flags2;
596         if (rev->pending.nr != 2)
597                 die("Need exactly one range.");
599         o1 = rev->pending.objects[0].item;
600         flags1 = o1->flags;
601         o2 = rev->pending.objects[1].item;
602         flags2 = o2->flags;
604         if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
605                 die("Not a range.");
607         init_patch_ids(ids);
609         /* given a range a..b get all patch ids for b..a */
610         init_revisions(&check_rev, prefix);
611         o1->flags ^= UNINTERESTING;
612         o2->flags ^= UNINTERESTING;
613         add_pending_object(&check_rev, o1, "o1");
614         add_pending_object(&check_rev, o2, "o2");
615         if (prepare_revision_walk(&check_rev))
616                 die("revision walk setup failed");
618         while ((commit = get_revision(&check_rev)) != NULL) {
619                 /* ignore merges */
620                 if (commit->parents && commit->parents->next)
621                         continue;
623                 add_commit_patch_id(commit, ids);
624         }
626         /* reset for next revision walk */
627         clear_commit_marks((struct commit *)o1,
628                         SEEN | UNINTERESTING | SHOWN | ADDED);
629         clear_commit_marks((struct commit *)o2,
630                         SEEN | UNINTERESTING | SHOWN | ADDED);
631         o1->flags = flags1;
632         o2->flags = flags2;
635 static void gen_message_id(struct rev_info *info, char *base)
637         const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
638         const char *email_start = strrchr(committer, '<');
639         const char *email_end = strrchr(committer, '>');
640         struct strbuf buf;
641         if (!email_start || !email_end || email_start > email_end - 1)
642                 die("Could not extract email from committer identity.");
643         strbuf_init(&buf, 0);
644         strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
645                     (unsigned long) time(NULL),
646                     (int)(email_end - email_start - 1), email_start + 1);
647         info->message_id = strbuf_detach(&buf, NULL);
650 static void make_cover_letter(struct rev_info *rev, int use_stdout,
651                               int numbered, int numbered_files,
652                               struct commit *origin,
653                               int nr, struct commit **list, struct commit *head)
655         const char *committer;
656         char *head_sha1;
657         const char *subject_start = NULL;
658         const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
659         const char *msg;
660         const char *extra_headers = rev->extra_headers;
661         struct shortlog log;
662         struct strbuf sb;
663         int i;
664         const char *encoding = "utf-8";
665         struct diff_options opts;
666         int need_8bit_cte = 0;
668         if (rev->commit_format != CMIT_FMT_EMAIL)
669                 die("Cover letter needs email format");
671         if (!use_stdout && reopen_stdout(numbered_files ?
672                                 NULL : "cover-letter", 0, rev->total))
673                 return;
675         head_sha1 = sha1_to_hex(head->object.sha1);
677         log_write_email_headers(rev, head_sha1, &subject_start, &extra_headers,
678                                 &need_8bit_cte);
680         committer = git_committer_info(0);
682         msg = body;
683         strbuf_init(&sb, 0);
684         pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
685                      encoding);
686         pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
687                       encoding, need_8bit_cte);
688         pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
689         printf("%s\n", sb.buf);
691         strbuf_release(&sb);
693         shortlog_init(&log);
694         log.wrap_lines = 1;
695         log.wrap = 72;
696         log.in1 = 2;
697         log.in2 = 4;
698         for (i = 0; i < nr; i++)
699                 shortlog_add_commit(&log, list[i]);
701         shortlog_output(&log);
703         /*
704          * We can only do diffstat with a unique reference point
705          */
706         if (!origin)
707                 return;
709         memcpy(&opts, &rev->diffopt, sizeof(opts));
710         opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
712         diff_setup_done(&opts);
714         diff_tree_sha1(origin->tree->object.sha1,
715                        head->tree->object.sha1,
716                        "", &opts);
717         diffcore_std(&opts);
718         diff_flush(&opts);
720         printf("\n");
723 static const char *clean_message_id(const char *msg_id)
725         char ch;
726         const char *a, *z, *m;
728         m = msg_id;
729         while ((ch = *m) && (isspace(ch) || (ch == '<')))
730                 m++;
731         a = m;
732         z = NULL;
733         while ((ch = *m)) {
734                 if (!isspace(ch) && (ch != '>'))
735                         z = m;
736                 m++;
737         }
738         if (!z)
739                 die("insane in-reply-to: %s", msg_id);
740         if (++z == m)
741                 return a;
742         return xmemdupz(a, z - a);
745 int cmd_format_patch(int argc, const char **argv, const char *prefix)
747         struct commit *commit;
748         struct commit **list = NULL;
749         struct rev_info rev;
750         int nr = 0, total, i, j;
751         int use_stdout = 0;
752         int start_number = -1;
753         int keep_subject = 0;
754         int numbered_files = 0;         /* _just_ numbers */
755         int subject_prefix = 0;
756         int ignore_if_in_upstream = 0;
757         int thread = 0;
758         int cover_letter = 0;
759         int boundary_count = 0;
760         int no_binary_diff = 0;
761         struct commit *origin = NULL, *head = NULL;
762         const char *in_reply_to = NULL;
763         struct patch_ids ids;
764         char *add_signoff = NULL;
765         struct strbuf buf;
767         git_config(git_format_config);
768         init_revisions(&rev, prefix);
769         rev.commit_format = CMIT_FMT_EMAIL;
770         rev.verbose_header = 1;
771         rev.diff = 1;
772         rev.combine_merges = 0;
773         rev.ignore_merges = 1;
774         DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
776         rev.subject_prefix = fmt_patch_subject_prefix;
778         /*
779          * Parse the arguments before setup_revisions(), or something
780          * like "git format-patch -o a123 HEAD^.." may fail; a123 is
781          * possibly a valid SHA1.
782          */
783         for (i = 1, j = 1; i < argc; i++) {
784                 if (!strcmp(argv[i], "--stdout"))
785                         use_stdout = 1;
786                 else if (!strcmp(argv[i], "-n") ||
787                                 !strcmp(argv[i], "--numbered"))
788                         numbered = 1;
789                 else if (!strcmp(argv[i], "-N") ||
790                                 !strcmp(argv[i], "--no-numbered")) {
791                         numbered = 0;
792                         auto_number = 0;
793                 }
794                 else if (!prefixcmp(argv[i], "--start-number="))
795                         start_number = strtol(argv[i] + 15, NULL, 10);
796                 else if (!strcmp(argv[i], "--numbered-files"))
797                         numbered_files = 1;
798                 else if (!strcmp(argv[i], "--start-number")) {
799                         i++;
800                         if (i == argc)
801                                 die("Need a number for --start-number");
802                         start_number = strtol(argv[i], NULL, 10);
803                 }
804                 else if (!prefixcmp(argv[i], "--cc=")) {
805                         ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
806                         extra_cc[extra_cc_nr++] = xstrdup(argv[i] + 5);
807                 }
808                 else if (!strcmp(argv[i], "-k") ||
809                                 !strcmp(argv[i], "--keep-subject")) {
810                         keep_subject = 1;
811                         rev.total = -1;
812                 }
813                 else if (!strcmp(argv[i], "--output-directory") ||
814                          !strcmp(argv[i], "-o")) {
815                         i++;
816                         if (argc <= i)
817                                 die("Which directory?");
818                         if (output_directory)
819                                 die("Two output directories?");
820                         output_directory = argv[i];
821                 }
822                 else if (!strcmp(argv[i], "--signoff") ||
823                          !strcmp(argv[i], "-s")) {
824                         const char *committer;
825                         const char *endpos;
826                         committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
827                         endpos = strchr(committer, '>');
828                         if (!endpos)
829                                 die("bogos committer info %s\n", committer);
830                         add_signoff = xmemdupz(committer, endpos - committer + 1);
831                 }
832                 else if (!strcmp(argv[i], "--attach")) {
833                         rev.mime_boundary = git_version_string;
834                         rev.no_inline = 1;
835                 }
836                 else if (!prefixcmp(argv[i], "--attach=")) {
837                         rev.mime_boundary = argv[i] + 9;
838                         rev.no_inline = 1;
839                 }
840                 else if (!strcmp(argv[i], "--inline")) {
841                         rev.mime_boundary = git_version_string;
842                         rev.no_inline = 0;
843                 }
844                 else if (!prefixcmp(argv[i], "--inline=")) {
845                         rev.mime_boundary = argv[i] + 9;
846                         rev.no_inline = 0;
847                 }
848                 else if (!strcmp(argv[i], "--ignore-if-in-upstream"))
849                         ignore_if_in_upstream = 1;
850                 else if (!strcmp(argv[i], "--thread"))
851                         thread = 1;
852                 else if (!prefixcmp(argv[i], "--in-reply-to="))
853                         in_reply_to = argv[i] + 14;
854                 else if (!strcmp(argv[i], "--in-reply-to")) {
855                         i++;
856                         if (i == argc)
857                                 die("Need a Message-Id for --in-reply-to");
858                         in_reply_to = argv[i];
859                 } else if (!prefixcmp(argv[i], "--subject-prefix=")) {
860                         subject_prefix = 1;
861                         rev.subject_prefix = argv[i] + 17;
862                 } else if (!prefixcmp(argv[i], "--suffix="))
863                         fmt_patch_suffix = argv[i] + 9;
864                 else if (!strcmp(argv[i], "--cover-letter"))
865                         cover_letter = 1;
866                 else if (!strcmp(argv[i], "--no-binary"))
867                         no_binary_diff = 1;
868                 else
869                         argv[j++] = argv[i];
870         }
871         argc = j;
873         strbuf_init(&buf, 0);
875         for (i = 0; i < extra_hdr_nr; i++) {
876                 strbuf_addstr(&buf, extra_hdr[i]);
877                 strbuf_addch(&buf, '\n');
878         }
880         if (extra_to_nr)
881                 strbuf_addstr(&buf, "To: ");
882         for (i = 0; i < extra_to_nr; i++) {
883                 if (i)
884                         strbuf_addstr(&buf, "    ");
885                 strbuf_addstr(&buf, extra_to[i]);
886                 if (i + 1 < extra_to_nr)
887                         strbuf_addch(&buf, ',');
888                 strbuf_addch(&buf, '\n');
889         }
891         if (extra_cc_nr)
892                 strbuf_addstr(&buf, "Cc: ");
893         for (i = 0; i < extra_cc_nr; i++) {
894                 if (i)
895                         strbuf_addstr(&buf, "    ");
896                 strbuf_addstr(&buf, extra_cc[i]);
897                 if (i + 1 < extra_cc_nr)
898                         strbuf_addch(&buf, ',');
899                 strbuf_addch(&buf, '\n');
900         }
902         rev.extra_headers = strbuf_detach(&buf, 0);
904         if (start_number < 0)
905                 start_number = 1;
906         if (numbered && keep_subject)
907                 die ("-n and -k are mutually exclusive.");
908         if (keep_subject && subject_prefix)
909                 die ("--subject-prefix and -k are mutually exclusive.");
910         if (numbered_files && use_stdout)
911                 die ("--numbered-files and --stdout are mutually exclusive.");
913         argc = setup_revisions(argc, argv, &rev, "HEAD");
914         if (argc > 1)
915                 die ("unrecognized argument: %s", argv[1]);
917         if (!rev.diffopt.output_format)
918                 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
920         if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
921                 DIFF_OPT_SET(&rev.diffopt, BINARY);
923         if (!output_directory && !use_stdout)
924                 output_directory = prefix;
926         if (output_directory) {
927                 if (use_stdout)
928                         die("standard output, or directory, which one?");
929                 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
930                         die("Could not create directory %s",
931                             output_directory);
932         }
934         if (rev.pending.nr == 1) {
935                 if (rev.max_count < 0 && !rev.show_root_diff) {
936                         /*
937                          * This is traditional behaviour of "git format-patch
938                          * origin" that prepares what the origin side still
939                          * does not have.
940                          */
941                         rev.pending.objects[0].item->flags |= UNINTERESTING;
942                         add_head_to_pending(&rev);
943                 }
944                 /*
945                  * Otherwise, it is "format-patch -22 HEAD", and/or
946                  * "format-patch --root HEAD".  The user wants
947                  * get_revision() to do the usual traversal.
948                  */
949         }
950         if (cover_letter) {
951                 /* remember the range */
952                 int i;
953                 for (i = 0; i < rev.pending.nr; i++) {
954                         struct object *o = rev.pending.objects[i].item;
955                         if (!(o->flags & UNINTERESTING))
956                                 head = (struct commit *)o;
957                 }
958                 /* We can't generate a cover letter without any patches */
959                 if (!head)
960                         return 0;
961         }
963         if (ignore_if_in_upstream)
964                 get_patch_ids(&rev, &ids, prefix);
966         if (!use_stdout)
967                 realstdout = xfdopen(xdup(1), "w");
969         if (prepare_revision_walk(&rev))
970                 die("revision walk setup failed");
971         rev.boundary = 1;
972         while ((commit = get_revision(&rev)) != NULL) {
973                 if (commit->object.flags & BOUNDARY) {
974                         boundary_count++;
975                         origin = (boundary_count == 1) ? commit : NULL;
976                         continue;
977                 }
979                 /* ignore merges */
980                 if (commit->parents && commit->parents->next)
981                         continue;
983                 if (ignore_if_in_upstream &&
984                                 has_commit_patch_id(commit, &ids))
985                         continue;
987                 nr++;
988                 list = xrealloc(list, nr * sizeof(list[0]));
989                 list[nr - 1] = commit;
990         }
991         total = nr;
992         if (!keep_subject && auto_number && total > 1)
993                 numbered = 1;
994         if (numbered)
995                 rev.total = total + start_number - 1;
996         if (in_reply_to)
997                 rev.ref_message_id = clean_message_id(in_reply_to);
998         if (cover_letter) {
999                 if (thread)
1000                         gen_message_id(&rev, "cover");
1001                 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1002                                   origin, nr, list, head);
1003                 total++;
1004                 start_number--;
1005         }
1006         rev.add_signoff = add_signoff;
1007         while (0 <= --nr) {
1008                 int shown;
1009                 commit = list[nr];
1010                 rev.nr = total - nr + (start_number - 1);
1011                 /* Make the second and subsequent mails replies to the first */
1012                 if (thread) {
1013                         /* Have we already had a message ID? */
1014                         if (rev.message_id) {
1015                                 /*
1016                                  * If we've got the ID to be a reply
1017                                  * to, discard the current ID;
1018                                  * otherwise, make everything a reply
1019                                  * to that.
1020                                  */
1021                                 if (rev.ref_message_id)
1022                                         free(rev.message_id);
1023                                 else
1024                                         rev.ref_message_id = rev.message_id;
1025                         }
1026                         gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1027                 }
1028                 if (!use_stdout && reopen_stdout(numbered_files ? NULL :
1029                                 get_oneline_for_filename(commit, keep_subject),
1030                                 rev.nr, rev.total))
1031                         die("Failed to create output files");
1032                 shown = log_tree_commit(&rev, commit);
1033                 free(commit->buffer);
1034                 commit->buffer = NULL;
1036                 /* We put one extra blank line between formatted
1037                  * patches and this flag is used by log-tree code
1038                  * to see if it needs to emit a LF before showing
1039                  * the log; when using one file per patch, we do
1040                  * not want the extra blank line.
1041                  */
1042                 if (!use_stdout)
1043                         rev.shown_one = 0;
1044                 if (shown) {
1045                         if (rev.mime_boundary)
1046                                 printf("\n--%s%s--\n\n\n",
1047                                        mime_boundary_leader,
1048                                        rev.mime_boundary);
1049                         else
1050                                 printf("-- \n%s\n\n", git_version_string);
1051                 }
1052                 if (!use_stdout)
1053                         fclose(stdout);
1054         }
1055         free(list);
1056         if (ignore_if_in_upstream)
1057                 free_patch_ids(&ids);
1058         return 0;
1061 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1063         unsigned char sha1[20];
1064         if (get_sha1(arg, sha1) == 0) {
1065                 struct commit *commit = lookup_commit_reference(sha1);
1066                 if (commit) {
1067                         commit->object.flags |= flags;
1068                         add_pending_object(revs, &commit->object, arg);
1069                         return 0;
1070                 }
1071         }
1072         return -1;
1075 static const char cherry_usage[] =
1076 "git-cherry [-v] <upstream> [<head>] [<limit>]";
1077 int cmd_cherry(int argc, const char **argv, const char *prefix)
1079         struct rev_info revs;
1080         struct patch_ids ids;
1081         struct commit *commit;
1082         struct commit_list *list = NULL;
1083         const char *upstream;
1084         const char *head = "HEAD";
1085         const char *limit = NULL;
1086         int verbose = 0;
1088         if (argc > 1 && !strcmp(argv[1], "-v")) {
1089                 verbose = 1;
1090                 argc--;
1091                 argv++;
1092         }
1094         switch (argc) {
1095         case 4:
1096                 limit = argv[3];
1097                 /* FALLTHROUGH */
1098         case 3:
1099                 head = argv[2];
1100                 /* FALLTHROUGH */
1101         case 2:
1102                 upstream = argv[1];
1103                 break;
1104         default:
1105                 usage(cherry_usage);
1106         }
1108         init_revisions(&revs, prefix);
1109         revs.diff = 1;
1110         revs.combine_merges = 0;
1111         revs.ignore_merges = 1;
1112         DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1114         if (add_pending_commit(head, &revs, 0))
1115                 die("Unknown commit %s", head);
1116         if (add_pending_commit(upstream, &revs, UNINTERESTING))
1117                 die("Unknown commit %s", upstream);
1119         /* Don't say anything if head and upstream are the same. */
1120         if (revs.pending.nr == 2) {
1121                 struct object_array_entry *o = revs.pending.objects;
1122                 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1123                         return 0;
1124         }
1126         get_patch_ids(&revs, &ids, prefix);
1128         if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1129                 die("Unknown commit %s", limit);
1131         /* reverse the list of commits */
1132         if (prepare_revision_walk(&revs))
1133                 die("revision walk setup failed");
1134         while ((commit = get_revision(&revs)) != NULL) {
1135                 /* ignore merges */
1136                 if (commit->parents && commit->parents->next)
1137                         continue;
1139                 commit_list_insert(commit, &list);
1140         }
1142         while (list) {
1143                 char sign = '+';
1145                 commit = list->item;
1146                 if (has_commit_patch_id(commit, &ids))
1147                         sign = '-';
1149                 if (verbose) {
1150                         struct strbuf buf;
1151                         strbuf_init(&buf, 0);
1152                         pretty_print_commit(CMIT_FMT_ONELINE, commit,
1153                                             &buf, 0, NULL, NULL, 0, 0);
1154                         printf("%c %s %s\n", sign,
1155                                sha1_to_hex(commit->object.sha1), buf.buf);
1156                         strbuf_release(&buf);
1157                 }
1158                 else {
1159                         printf("%c %s\n", sign,
1160                                sha1_to_hex(commit->object.sha1));
1161                 }
1163                 list = list->next;
1164         }
1166         free_patch_ids(&ids);
1167         return 0;