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