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