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