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