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