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