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