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