]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/log.c
environment.h: move declarations for environment.c functions from cache.h
[thirdparty/git.git] / builtin / log.c
1 /*
2 * Builtin "git log" and related commands (show, whatchanged)
3 *
4 * (C) Copyright 2006 Linus Torvalds
5 * 2006 Junio Hamano
6 */
7 #include "git-compat-util.h"
8 #include "abspath.h"
9 #include "alloc.h"
10 #include "config.h"
11 #include "environment.h"
12 #include "gettext.h"
13 #include "hex.h"
14 #include "refs.h"
15 #include "object-store.h"
16 #include "color.h"
17 #include "commit.h"
18 #include "diff.h"
19 #include "diff-merges.h"
20 #include "revision.h"
21 #include "log-tree.h"
22 #include "builtin.h"
23 #include "tag.h"
24 #include "reflog-walk.h"
25 #include "patch-ids.h"
26 #include "run-command.h"
27 #include "shortlog.h"
28 #include "remote.h"
29 #include "string-list.h"
30 #include "parse-options.h"
31 #include "line-log.h"
32 #include "branch.h"
33 #include "streaming.h"
34 #include "version.h"
35 #include "mailmap.h"
36 #include "gpg-interface.h"
37 #include "progress.h"
38 #include "commit-slab.h"
39 #include "repository.h"
40 #include "commit-reach.h"
41 #include "range-diff.h"
42 #include "tmp-objdir.h"
43
44 #define MAIL_DEFAULT_WRAP 72
45 #define COVER_FROM_AUTO_MAX_SUBJECT_LEN 100
46 #define FORMAT_PATCH_NAME_MAX_DEFAULT 64
47
48 /* Set a default date-time format for git log ("log.date" config variable) */
49 static const char *default_date_mode = NULL;
50
51 static int default_abbrev_commit;
52 static int default_show_root = 1;
53 static int default_follow;
54 static int default_show_signature;
55 static int default_encode_email_headers = 1;
56 static int decoration_style;
57 static int decoration_given;
58 static int use_mailmap_config = 1;
59 static unsigned int force_in_body_from;
60 static int stdout_mboxrd;
61 static const char *fmt_patch_subject_prefix = "PATCH";
62 static int fmt_patch_name_max = FORMAT_PATCH_NAME_MAX_DEFAULT;
63 static const char *fmt_pretty;
64
65 static const char * const builtin_log_usage[] = {
66 N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
67 N_("git show [<options>] <object>..."),
68 NULL
69 };
70
71 struct line_opt_callback_data {
72 struct rev_info *rev;
73 const char *prefix;
74 struct string_list args;
75 };
76
77 static int session_is_interactive(void)
78 {
79 return isatty(1) || pager_in_use();
80 }
81
82 static int auto_decoration_style(void)
83 {
84 return session_is_interactive() ? DECORATE_SHORT_REFS : 0;
85 }
86
87 static int parse_decoration_style(const char *value)
88 {
89 switch (git_parse_maybe_bool(value)) {
90 case 1:
91 return DECORATE_SHORT_REFS;
92 case 0:
93 return 0;
94 default:
95 break;
96 }
97 if (!strcmp(value, "full"))
98 return DECORATE_FULL_REFS;
99 else if (!strcmp(value, "short"))
100 return DECORATE_SHORT_REFS;
101 else if (!strcmp(value, "auto"))
102 return auto_decoration_style();
103 /*
104 * Please update _git_log() in git-completion.bash when you
105 * add new decoration styles.
106 */
107 return -1;
108 }
109
110 static int use_default_decoration_filter = 1;
111 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
112 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
113 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
114
115 static int clear_decorations_callback(const struct option *opt,
116 const char *arg, int unset)
117 {
118 string_list_clear(&decorate_refs_include, 0);
119 string_list_clear(&decorate_refs_exclude, 0);
120 use_default_decoration_filter = 0;
121 return 0;
122 }
123
124 static int decorate_callback(const struct option *opt, const char *arg, int unset)
125 {
126 if (unset)
127 decoration_style = 0;
128 else if (arg)
129 decoration_style = parse_decoration_style(arg);
130 else
131 decoration_style = DECORATE_SHORT_REFS;
132
133 if (decoration_style < 0)
134 die(_("invalid --decorate option: %s"), arg);
135
136 decoration_given = 1;
137
138 return 0;
139 }
140
141 static int log_line_range_callback(const struct option *option, const char *arg, int unset)
142 {
143 struct line_opt_callback_data *data = option->value;
144
145 BUG_ON_OPT_NEG(unset);
146
147 if (!arg)
148 return -1;
149
150 data->rev->line_level_traverse = 1;
151 string_list_append(&data->args, arg);
152
153 return 0;
154 }
155
156 static void init_log_defaults(void)
157 {
158 init_diff_ui_defaults();
159
160 decoration_style = auto_decoration_style();
161 }
162
163 static void cmd_log_init_defaults(struct rev_info *rev)
164 {
165 if (fmt_pretty)
166 get_commit_format(fmt_pretty, rev);
167 if (default_follow)
168 rev->diffopt.flags.default_follow_renames = 1;
169 rev->verbose_header = 1;
170 rev->diffopt.flags.recursive = 1;
171 rev->diffopt.stat_width = -1; /* use full terminal width */
172 rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
173 rev->abbrev_commit = default_abbrev_commit;
174 rev->show_root_diff = default_show_root;
175 rev->subject_prefix = fmt_patch_subject_prefix;
176 rev->patch_name_max = fmt_patch_name_max;
177 rev->show_signature = default_show_signature;
178 rev->encode_email_headers = default_encode_email_headers;
179 rev->diffopt.flags.allow_textconv = 1;
180
181 if (default_date_mode)
182 parse_date_format(default_date_mode, &rev->date_mode);
183 }
184
185 static void set_default_decoration_filter(struct decoration_filter *decoration_filter)
186 {
187 int i;
188 char *value = NULL;
189 struct string_list *include = decoration_filter->include_ref_pattern;
190 const struct string_list *config_exclude =
191 git_config_get_value_multi("log.excludeDecoration");
192
193 if (config_exclude) {
194 struct string_list_item *item;
195 for_each_string_list_item(item, config_exclude)
196 string_list_append(decoration_filter->exclude_ref_config_pattern,
197 item->string);
198 }
199
200 /*
201 * By default, decorate_all is disabled. Enable it if
202 * log.initialDecorationSet=all. Don't ever disable it by config,
203 * since the command-line takes precedent.
204 */
205 if (use_default_decoration_filter &&
206 !git_config_get_string("log.initialdecorationset", &value) &&
207 !strcmp("all", value))
208 use_default_decoration_filter = 0;
209 free(value);
210
211 if (!use_default_decoration_filter ||
212 decoration_filter->exclude_ref_pattern->nr ||
213 decoration_filter->include_ref_pattern->nr ||
214 decoration_filter->exclude_ref_config_pattern->nr)
215 return;
216
217 /*
218 * No command-line or config options were given, so
219 * populate with sensible defaults.
220 */
221 for (i = 0; i < ARRAY_SIZE(ref_namespace); i++) {
222 if (!ref_namespace[i].decoration)
223 continue;
224
225 string_list_append(include, ref_namespace[i].ref);
226 }
227 }
228
229 static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
230 struct rev_info *rev, struct setup_revision_opt *opt)
231 {
232 struct userformat_want w;
233 int quiet = 0, source = 0, mailmap;
234 static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
235 struct decoration_filter decoration_filter = {
236 .exclude_ref_pattern = &decorate_refs_exclude,
237 .include_ref_pattern = &decorate_refs_include,
238 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
239 };
240 static struct revision_sources revision_sources;
241
242 const struct option builtin_log_options[] = {
243 OPT__QUIET(&quiet, N_("suppress diff output")),
244 OPT_BOOL(0, "source", &source, N_("show source")),
245 OPT_BOOL(0, "use-mailmap", &mailmap, N_("use mail map file")),
246 OPT_ALIAS(0, "mailmap", "use-mailmap"),
247 OPT_CALLBACK_F(0, "clear-decorations", NULL, NULL,
248 N_("clear all previously-defined decoration filters"),
249 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
250 clear_decorations_callback),
251 OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
252 N_("pattern"), N_("only decorate refs that match <pattern>")),
253 OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
254 N_("pattern"), N_("do not decorate refs that match <pattern>")),
255 OPT_CALLBACK_F(0, "decorate", NULL, NULL, N_("decorate options"),
256 PARSE_OPT_OPTARG, decorate_callback),
257 OPT_CALLBACK('L', NULL, &line_cb, "range:file",
258 N_("trace the evolution of line range <start>,<end> or function :<funcname> in <file>"),
259 log_line_range_callback),
260 OPT_END()
261 };
262
263 line_cb.rev = rev;
264 line_cb.prefix = prefix;
265
266 mailmap = use_mailmap_config;
267 argc = parse_options(argc, argv, prefix,
268 builtin_log_options, builtin_log_usage,
269 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
270 PARSE_OPT_KEEP_DASHDASH);
271
272 if (quiet)
273 rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
274 argc = setup_revisions(argc, argv, rev, opt);
275
276 /* Any arguments at this point are not recognized */
277 if (argc > 1)
278 die(_("unrecognized argument: %s"), argv[1]);
279
280 if (rev->line_level_traverse && rev->prune_data.nr)
281 die(_("-L<range>:<file> cannot be used with pathspec"));
282
283 memset(&w, 0, sizeof(w));
284 userformat_find_requirements(NULL, &w);
285
286 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
287 rev->show_notes = 1;
288 if (rev->show_notes)
289 load_display_notes(&rev->notes_opt);
290
291 if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
292 rev->diffopt.filter || rev->diffopt.flags.follow_renames)
293 rev->always_show_header = 0;
294
295 if (source || w.source) {
296 init_revision_sources(&revision_sources);
297 rev->sources = &revision_sources;
298 }
299
300 if (mailmap) {
301 rev->mailmap = xmalloc(sizeof(struct string_list));
302 string_list_init_nodup(rev->mailmap);
303 read_mailmap(rev->mailmap);
304 }
305
306 if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
307 /*
308 * "log --pretty=raw" is special; ignore UI oriented
309 * configuration variables such as decoration.
310 */
311 if (!decoration_given)
312 decoration_style = 0;
313 if (!rev->abbrev_commit_given)
314 rev->abbrev_commit = 0;
315 }
316
317 if (rev->commit_format == CMIT_FMT_USERFORMAT) {
318 if (!w.decorate) {
319 /*
320 * Disable decoration loading if the format will not
321 * show them anyway.
322 */
323 decoration_style = 0;
324 } else if (!decoration_style) {
325 /*
326 * If we are going to show them, make sure we do load
327 * them here, but taking care not to override a
328 * specific style set by config or --decorate.
329 */
330 decoration_style = DECORATE_SHORT_REFS;
331 }
332 }
333
334 if (decoration_style || rev->simplify_by_decoration) {
335 set_default_decoration_filter(&decoration_filter);
336
337 if (decoration_style)
338 rev->show_decorations = 1;
339
340 load_ref_decorations(&decoration_filter, decoration_style);
341 }
342
343 if (rev->line_level_traverse)
344 line_log_init(rev, line_cb.prefix, &line_cb.args);
345
346 setup_pager();
347 }
348
349 static void cmd_log_init(int argc, const char **argv, const char *prefix,
350 struct rev_info *rev, struct setup_revision_opt *opt)
351 {
352 cmd_log_init_defaults(rev);
353 cmd_log_init_finish(argc, argv, prefix, rev, opt);
354 }
355
356 static int cmd_log_deinit(int ret, struct rev_info *rev)
357 {
358 release_revisions(rev);
359 return ret;
360 }
361
362 /*
363 * This gives a rough estimate for how many commits we
364 * will print out in the list.
365 */
366 static int estimate_commit_count(struct commit_list *list)
367 {
368 int n = 0;
369
370 while (list) {
371 struct commit *commit = list->item;
372 unsigned int flags = commit->object.flags;
373 list = list->next;
374 if (!(flags & (TREESAME | UNINTERESTING)))
375 n++;
376 }
377 return n;
378 }
379
380 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
381 {
382 if (rev->shown_one) {
383 rev->shown_one = 0;
384 if (rev->commit_format != CMIT_FMT_ONELINE)
385 putchar(rev->diffopt.line_termination);
386 }
387 fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
388 }
389
390 static struct itimerval early_output_timer;
391
392 static void log_show_early(struct rev_info *revs, struct commit_list *list)
393 {
394 int i = revs->early_output;
395 int show_header = 1;
396 int no_free = revs->diffopt.no_free;
397
398 revs->diffopt.no_free = 0;
399 sort_in_topological_order(&list, revs->sort_order);
400 while (list && i) {
401 struct commit *commit = list->item;
402 switch (simplify_commit(revs, commit)) {
403 case commit_show:
404 if (show_header) {
405 int n = estimate_commit_count(list);
406 show_early_header(revs, "incomplete", n);
407 show_header = 0;
408 }
409 log_tree_commit(revs, commit);
410 i--;
411 break;
412 case commit_ignore:
413 break;
414 case commit_error:
415 revs->diffopt.no_free = no_free;
416 diff_free(&revs->diffopt);
417 return;
418 }
419 list = list->next;
420 }
421
422 /* Did we already get enough commits for the early output? */
423 if (!i) {
424 revs->diffopt.no_free = 0;
425 diff_free(&revs->diffopt);
426 return;
427 }
428
429 /*
430 * ..if no, then repeat it twice a second until we
431 * do.
432 *
433 * NOTE! We don't use "it_interval", because if the
434 * reader isn't listening, we want our output to be
435 * throttled by the writing, and not have the timer
436 * trigger every second even if we're blocked on a
437 * reader!
438 */
439 early_output_timer.it_value.tv_sec = 0;
440 early_output_timer.it_value.tv_usec = 500000;
441 setitimer(ITIMER_REAL, &early_output_timer, NULL);
442 }
443
444 static void early_output(int signal UNUSED)
445 {
446 show_early_output = log_show_early;
447 }
448
449 static void setup_early_output(void)
450 {
451 struct sigaction sa;
452
453 /*
454 * Set up the signal handler, minimally intrusively:
455 * we only set a single volatile integer word (not
456 * using sigatomic_t - trying to avoid unnecessary
457 * system dependencies and headers), and using
458 * SA_RESTART.
459 */
460 memset(&sa, 0, sizeof(sa));
461 sa.sa_handler = early_output;
462 sigemptyset(&sa.sa_mask);
463 sa.sa_flags = SA_RESTART;
464 sigaction(SIGALRM, &sa, NULL);
465
466 /*
467 * If we can get the whole output in less than a
468 * tenth of a second, don't even bother doing the
469 * early-output thing..
470 *
471 * This is a one-time-only trigger.
472 */
473 early_output_timer.it_value.tv_sec = 0;
474 early_output_timer.it_value.tv_usec = 100000;
475 setitimer(ITIMER_REAL, &early_output_timer, NULL);
476 }
477
478 static void finish_early_output(struct rev_info *rev)
479 {
480 int n = estimate_commit_count(rev->commits);
481 signal(SIGALRM, SIG_IGN);
482 show_early_header(rev, "done", n);
483 }
484
485 static int cmd_log_walk_no_free(struct rev_info *rev)
486 {
487 struct commit *commit;
488 int saved_nrl = 0;
489 int saved_dcctc = 0;
490
491 if (rev->remerge_diff) {
492 rev->remerge_objdir = tmp_objdir_create("remerge-diff");
493 if (!rev->remerge_objdir)
494 die(_("unable to create temporary object directory"));
495 tmp_objdir_replace_primary_odb(rev->remerge_objdir, 1);
496 }
497
498 if (rev->early_output)
499 setup_early_output();
500
501 if (prepare_revision_walk(rev))
502 die(_("revision walk setup failed"));
503
504 if (rev->early_output)
505 finish_early_output(rev);
506
507 /*
508 * For --check and --exit-code, the exit code is based on CHECK_FAILED
509 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
510 * retain that state information if replacing rev->diffopt in this loop
511 */
512 while ((commit = get_revision(rev)) != NULL) {
513 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
514 /*
515 * We decremented max_count in get_revision,
516 * but we didn't actually show the commit.
517 */
518 rev->max_count++;
519 if (!rev->reflog_info) {
520 /*
521 * We may show a given commit multiple times when
522 * walking the reflogs.
523 */
524 free_commit_buffer(the_repository->parsed_objects,
525 commit);
526 free_commit_list(commit->parents);
527 commit->parents = NULL;
528 }
529 if (saved_nrl < rev->diffopt.needed_rename_limit)
530 saved_nrl = rev->diffopt.needed_rename_limit;
531 if (rev->diffopt.degraded_cc_to_c)
532 saved_dcctc = 1;
533 }
534 rev->diffopt.degraded_cc_to_c = saved_dcctc;
535 rev->diffopt.needed_rename_limit = saved_nrl;
536
537 if (rev->remerge_diff) {
538 tmp_objdir_destroy(rev->remerge_objdir);
539 rev->remerge_objdir = NULL;
540 }
541
542 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
543 rev->diffopt.flags.check_failed) {
544 return 02;
545 }
546 return diff_result_code(&rev->diffopt, 0);
547 }
548
549 static int cmd_log_walk(struct rev_info *rev)
550 {
551 int retval;
552
553 rev->diffopt.no_free = 1;
554 retval = cmd_log_walk_no_free(rev);
555 rev->diffopt.no_free = 0;
556 diff_free(&rev->diffopt);
557 return retval;
558 }
559
560 static int git_log_config(const char *var, const char *value, void *cb)
561 {
562 const char *slot_name;
563
564 if (!strcmp(var, "format.pretty"))
565 return git_config_string(&fmt_pretty, var, value);
566 if (!strcmp(var, "format.subjectprefix"))
567 return git_config_string(&fmt_patch_subject_prefix, var, value);
568 if (!strcmp(var, "format.filenamemaxlength")) {
569 fmt_patch_name_max = git_config_int(var, value);
570 return 0;
571 }
572 if (!strcmp(var, "format.encodeemailheaders")) {
573 default_encode_email_headers = git_config_bool(var, value);
574 return 0;
575 }
576 if (!strcmp(var, "log.abbrevcommit")) {
577 default_abbrev_commit = git_config_bool(var, value);
578 return 0;
579 }
580 if (!strcmp(var, "log.date"))
581 return git_config_string(&default_date_mode, var, value);
582 if (!strcmp(var, "log.decorate")) {
583 decoration_style = parse_decoration_style(value);
584 if (decoration_style < 0)
585 decoration_style = 0; /* maybe warn? */
586 return 0;
587 }
588 if (!strcmp(var, "log.diffmerges"))
589 return diff_merges_config(value);
590 if (!strcmp(var, "log.showroot")) {
591 default_show_root = git_config_bool(var, value);
592 return 0;
593 }
594 if (!strcmp(var, "log.follow")) {
595 default_follow = git_config_bool(var, value);
596 return 0;
597 }
598 if (skip_prefix(var, "color.decorate.", &slot_name))
599 return parse_decorate_color_config(var, slot_name, value);
600 if (!strcmp(var, "log.mailmap")) {
601 use_mailmap_config = git_config_bool(var, value);
602 return 0;
603 }
604 if (!strcmp(var, "log.showsignature")) {
605 default_show_signature = git_config_bool(var, value);
606 return 0;
607 }
608
609 return git_diff_ui_config(var, value, cb);
610 }
611
612 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
613 {
614 struct rev_info rev;
615 struct setup_revision_opt opt;
616
617 init_log_defaults();
618 git_config(git_log_config, NULL);
619
620 repo_init_revisions(the_repository, &rev, prefix);
621 git_config(grep_config, &rev.grep_filter);
622
623 rev.diff = 1;
624 rev.simplify_history = 0;
625 memset(&opt, 0, sizeof(opt));
626 opt.def = "HEAD";
627 opt.revarg_opt = REVARG_COMMITTISH;
628 cmd_log_init(argc, argv, prefix, &rev, &opt);
629 if (!rev.diffopt.output_format)
630 rev.diffopt.output_format = DIFF_FORMAT_RAW;
631 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
632 }
633
634 static void show_tagger(const char *buf, struct rev_info *rev)
635 {
636 struct strbuf out = STRBUF_INIT;
637 struct pretty_print_context pp = {0};
638
639 pp.fmt = rev->commit_format;
640 pp.date_mode = rev->date_mode;
641 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
642 fprintf(rev->diffopt.file, "%s", out.buf);
643 strbuf_release(&out);
644 }
645
646 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
647 {
648 struct object_id oidc;
649 struct object_context obj_context;
650 char *buf;
651 unsigned long size;
652
653 fflush(rev->diffopt.file);
654 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
655 !rev->diffopt.flags.allow_textconv)
656 return stream_blob_to_fd(1, oid, NULL, 0);
657
658 if (get_oid_with_context(the_repository, obj_name,
659 GET_OID_RECORD_PATH,
660 &oidc, &obj_context))
661 die(_("not a valid object name %s"), obj_name);
662 if (!obj_context.path ||
663 !textconv_object(the_repository, obj_context.path,
664 obj_context.mode, &oidc, 1, &buf, &size)) {
665 free(obj_context.path);
666 return stream_blob_to_fd(1, oid, NULL, 0);
667 }
668
669 if (!buf)
670 die(_("git show %s: bad file"), obj_name);
671
672 write_or_die(1, buf, size);
673 free(obj_context.path);
674 return 0;
675 }
676
677 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
678 {
679 unsigned long size;
680 enum object_type type;
681 char *buf = read_object_file(oid, &type, &size);
682 int offset = 0;
683
684 if (!buf)
685 return error(_("could not read object %s"), oid_to_hex(oid));
686
687 assert(type == OBJ_TAG);
688 while (offset < size && buf[offset] != '\n') {
689 int new_offset = offset + 1;
690 const char *ident;
691 while (new_offset < size && buf[new_offset++] != '\n')
692 ; /* do nothing */
693 if (skip_prefix(buf + offset, "tagger ", &ident))
694 show_tagger(ident, rev);
695 offset = new_offset;
696 }
697
698 if (offset < size)
699 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
700 free(buf);
701 return 0;
702 }
703
704 static int show_tree_object(const struct object_id *oid UNUSED,
705 struct strbuf *base UNUSED,
706 const char *pathname, unsigned mode,
707 void *context)
708 {
709 FILE *file = context;
710 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
711 return 0;
712 }
713
714 static void show_setup_revisions_tweak(struct rev_info *rev,
715 struct setup_revision_opt *opt)
716 {
717 if (rev->first_parent_only)
718 diff_merges_default_to_first_parent(rev);
719 else
720 diff_merges_default_to_dense_combined(rev);
721 if (!rev->diffopt.output_format)
722 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
723 }
724
725 int cmd_show(int argc, const char **argv, const char *prefix)
726 {
727 struct rev_info rev;
728 unsigned int i;
729 struct setup_revision_opt opt;
730 struct pathspec match_all;
731 int ret = 0;
732
733 init_log_defaults();
734 git_config(git_log_config, NULL);
735
736 if (the_repository->gitdir) {
737 prepare_repo_settings(the_repository);
738 the_repository->settings.command_requires_full_index = 0;
739 }
740
741 memset(&match_all, 0, sizeof(match_all));
742 repo_init_revisions(the_repository, &rev, prefix);
743 git_config(grep_config, &rev.grep_filter);
744
745 rev.diff = 1;
746 rev.always_show_header = 1;
747 rev.no_walk = 1;
748 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
749
750 memset(&opt, 0, sizeof(opt));
751 opt.def = "HEAD";
752 opt.tweak = show_setup_revisions_tweak;
753 cmd_log_init(argc, argv, prefix, &rev, &opt);
754
755 if (!rev.no_walk)
756 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
757
758 rev.diffopt.no_free = 1;
759 for (i = 0; i < rev.pending.nr && !ret; i++) {
760 struct object *o = rev.pending.objects[i].item;
761 const char *name = rev.pending.objects[i].name;
762 switch (o->type) {
763 case OBJ_BLOB:
764 ret = show_blob_object(&o->oid, &rev, name);
765 break;
766 case OBJ_TAG: {
767 struct tag *t = (struct tag *)o;
768 struct object_id *oid = get_tagged_oid(t);
769
770 if (rev.shown_one)
771 putchar('\n');
772 fprintf(rev.diffopt.file, "%stag %s%s\n",
773 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
774 t->tag,
775 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
776 ret = show_tag_object(&o->oid, &rev);
777 rev.shown_one = 1;
778 if (ret)
779 break;
780 o = parse_object(the_repository, oid);
781 if (!o)
782 ret = error(_("could not read object %s"),
783 oid_to_hex(oid));
784 rev.pending.objects[i].item = o;
785 i--;
786 break;
787 }
788 case OBJ_TREE:
789 if (rev.shown_one)
790 putchar('\n');
791 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
792 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
793 name,
794 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
795 read_tree(the_repository, (struct tree *)o,
796 &match_all, show_tree_object,
797 rev.diffopt.file);
798 rev.shown_one = 1;
799 break;
800 case OBJ_COMMIT:
801 {
802 struct object_array old;
803 struct object_array blank = OBJECT_ARRAY_INIT;
804
805 memcpy(&old, &rev.pending, sizeof(old));
806 memcpy(&rev.pending, &blank, sizeof(rev.pending));
807
808 add_object_array(o, name, &rev.pending);
809 ret = cmd_log_walk_no_free(&rev);
810
811 /*
812 * No need for
813 * object_array_clear(&pending). It was
814 * cleared already in prepare_revision_walk()
815 */
816 memcpy(&rev.pending, &old, sizeof(rev.pending));
817 break;
818 }
819 default:
820 ret = error(_("unknown type: %d"), o->type);
821 }
822 }
823
824 rev.diffopt.no_free = 0;
825 diff_free(&rev.diffopt);
826
827 return cmd_log_deinit(ret, &rev);
828 }
829
830 /*
831 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
832 */
833 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
834 {
835 struct rev_info rev;
836 struct setup_revision_opt opt;
837
838 init_log_defaults();
839 git_config(git_log_config, NULL);
840
841 repo_init_revisions(the_repository, &rev, prefix);
842 init_reflog_walk(&rev.reflog_info);
843 git_config(grep_config, &rev.grep_filter);
844
845 rev.verbose_header = 1;
846 memset(&opt, 0, sizeof(opt));
847 opt.def = "HEAD";
848 cmd_log_init_defaults(&rev);
849 rev.abbrev_commit = 1;
850 rev.commit_format = CMIT_FMT_ONELINE;
851 rev.use_terminator = 1;
852 rev.always_show_header = 1;
853 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
854
855 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
856 }
857
858 static void log_setup_revisions_tweak(struct rev_info *rev,
859 struct setup_revision_opt *opt)
860 {
861 if (rev->diffopt.flags.default_follow_renames &&
862 rev->prune_data.nr == 1)
863 rev->diffopt.flags.follow_renames = 1;
864
865 if (rev->first_parent_only)
866 diff_merges_default_to_first_parent(rev);
867 }
868
869 int cmd_log(int argc, const char **argv, const char *prefix)
870 {
871 struct rev_info rev;
872 struct setup_revision_opt opt;
873
874 init_log_defaults();
875 git_config(git_log_config, NULL);
876
877 repo_init_revisions(the_repository, &rev, prefix);
878 git_config(grep_config, &rev.grep_filter);
879
880 rev.always_show_header = 1;
881 memset(&opt, 0, sizeof(opt));
882 opt.def = "HEAD";
883 opt.revarg_opt = REVARG_COMMITTISH;
884 opt.tweak = log_setup_revisions_tweak;
885 cmd_log_init(argc, argv, prefix, &rev, &opt);
886 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
887 }
888
889 /* format-patch */
890
891 static const char *fmt_patch_suffix = ".patch";
892 static int numbered = 0;
893 static int auto_number = 1;
894
895 static char *default_attach = NULL;
896
897 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
898 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
899 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
900
901 static void add_header(const char *value)
902 {
903 struct string_list_item *item;
904 int len = strlen(value);
905 while (len && value[len - 1] == '\n')
906 len--;
907
908 if (!strncasecmp(value, "to: ", 4)) {
909 item = string_list_append(&extra_to, value + 4);
910 len -= 4;
911 } else if (!strncasecmp(value, "cc: ", 4)) {
912 item = string_list_append(&extra_cc, value + 4);
913 len -= 4;
914 } else {
915 item = string_list_append(&extra_hdr, value);
916 }
917
918 item->string[len] = '\0';
919 }
920
921 enum cover_setting {
922 COVER_UNSET,
923 COVER_OFF,
924 COVER_ON,
925 COVER_AUTO
926 };
927
928 enum thread_level {
929 THREAD_UNSET,
930 THREAD_SHALLOW,
931 THREAD_DEEP
932 };
933
934 enum cover_from_description {
935 COVER_FROM_NONE,
936 COVER_FROM_MESSAGE,
937 COVER_FROM_SUBJECT,
938 COVER_FROM_AUTO
939 };
940
941 enum auto_base_setting {
942 AUTO_BASE_NEVER,
943 AUTO_BASE_ALWAYS,
944 AUTO_BASE_WHEN_ABLE
945 };
946
947 static enum thread_level thread;
948 static int do_signoff;
949 static enum auto_base_setting auto_base;
950 static char *from;
951 static const char *signature = git_version_string;
952 static const char *signature_file;
953 static enum cover_setting config_cover_letter;
954 static const char *config_output_directory;
955 static enum cover_from_description cover_from_description_mode = COVER_FROM_MESSAGE;
956 static int show_notes;
957 static struct display_notes_opt notes_opt;
958
959 static enum cover_from_description parse_cover_from_description(const char *arg)
960 {
961 if (!arg || !strcmp(arg, "default"))
962 return COVER_FROM_MESSAGE;
963 else if (!strcmp(arg, "none"))
964 return COVER_FROM_NONE;
965 else if (!strcmp(arg, "message"))
966 return COVER_FROM_MESSAGE;
967 else if (!strcmp(arg, "subject"))
968 return COVER_FROM_SUBJECT;
969 else if (!strcmp(arg, "auto"))
970 return COVER_FROM_AUTO;
971 else
972 die(_("%s: invalid cover from description mode"), arg);
973 }
974
975 static int git_format_config(const char *var, const char *value, void *cb)
976 {
977 if (!strcmp(var, "format.headers")) {
978 if (!value)
979 die(_("format.headers without value"));
980 add_header(value);
981 return 0;
982 }
983 if (!strcmp(var, "format.suffix"))
984 return git_config_string(&fmt_patch_suffix, var, value);
985 if (!strcmp(var, "format.to")) {
986 if (!value)
987 return config_error_nonbool(var);
988 string_list_append(&extra_to, value);
989 return 0;
990 }
991 if (!strcmp(var, "format.cc")) {
992 if (!value)
993 return config_error_nonbool(var);
994 string_list_append(&extra_cc, value);
995 return 0;
996 }
997 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
998 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
999 return 0;
1000 }
1001 if (!strcmp(var, "format.numbered")) {
1002 if (value && !strcasecmp(value, "auto")) {
1003 auto_number = 1;
1004 return 0;
1005 }
1006 numbered = git_config_bool(var, value);
1007 auto_number = auto_number && numbered;
1008 return 0;
1009 }
1010 if (!strcmp(var, "format.attach")) {
1011 if (value && *value)
1012 default_attach = xstrdup(value);
1013 else if (value && !*value)
1014 FREE_AND_NULL(default_attach);
1015 else
1016 default_attach = xstrdup(git_version_string);
1017 return 0;
1018 }
1019 if (!strcmp(var, "format.thread")) {
1020 if (value && !strcasecmp(value, "deep")) {
1021 thread = THREAD_DEEP;
1022 return 0;
1023 }
1024 if (value && !strcasecmp(value, "shallow")) {
1025 thread = THREAD_SHALLOW;
1026 return 0;
1027 }
1028 thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
1029 return 0;
1030 }
1031 if (!strcmp(var, "format.signoff")) {
1032 do_signoff = git_config_bool(var, value);
1033 return 0;
1034 }
1035 if (!strcmp(var, "format.signature"))
1036 return git_config_string(&signature, var, value);
1037 if (!strcmp(var, "format.signaturefile"))
1038 return git_config_pathname(&signature_file, var, value);
1039 if (!strcmp(var, "format.coverletter")) {
1040 if (value && !strcasecmp(value, "auto")) {
1041 config_cover_letter = COVER_AUTO;
1042 return 0;
1043 }
1044 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
1045 return 0;
1046 }
1047 if (!strcmp(var, "format.outputdirectory"))
1048 return git_config_string(&config_output_directory, var, value);
1049 if (!strcmp(var, "format.useautobase")) {
1050 if (value && !strcasecmp(value, "whenAble")) {
1051 auto_base = AUTO_BASE_WHEN_ABLE;
1052 return 0;
1053 }
1054 auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
1055 return 0;
1056 }
1057 if (!strcmp(var, "format.from")) {
1058 int b = git_parse_maybe_bool(value);
1059 free(from);
1060 if (b < 0)
1061 from = xstrdup(value);
1062 else if (b)
1063 from = xstrdup(git_committer_info(IDENT_NO_DATE));
1064 else
1065 from = NULL;
1066 return 0;
1067 }
1068 if (!strcmp(var, "format.forceinbodyfrom")) {
1069 force_in_body_from = git_config_bool(var, value);
1070 return 0;
1071 }
1072 if (!strcmp(var, "format.notes")) {
1073 int b = git_parse_maybe_bool(value);
1074 if (b < 0)
1075 enable_ref_display_notes(&notes_opt, &show_notes, value);
1076 else if (b)
1077 enable_default_display_notes(&notes_opt, &show_notes);
1078 else
1079 disable_display_notes(&notes_opt, &show_notes);
1080 return 0;
1081 }
1082 if (!strcmp(var, "format.coverfromdescription")) {
1083 cover_from_description_mode = parse_cover_from_description(value);
1084 return 0;
1085 }
1086 if (!strcmp(var, "format.mboxrd")) {
1087 stdout_mboxrd = git_config_bool(var, value);
1088 return 0;
1089 }
1090
1091 return git_log_config(var, value, cb);
1092 }
1093
1094 static const char *output_directory = NULL;
1095 static int outdir_offset;
1096
1097 static int open_next_file(struct commit *commit, const char *subject,
1098 struct rev_info *rev, int quiet)
1099 {
1100 struct strbuf filename = STRBUF_INIT;
1101
1102 if (output_directory) {
1103 strbuf_addstr(&filename, output_directory);
1104 strbuf_complete(&filename, '/');
1105 }
1106
1107 if (rev->numbered_files)
1108 strbuf_addf(&filename, "%d", rev->nr);
1109 else if (commit)
1110 fmt_output_commit(&filename, commit, rev);
1111 else
1112 fmt_output_subject(&filename, subject, rev);
1113
1114 if (!quiet)
1115 printf("%s\n", filename.buf + outdir_offset);
1116
1117 if (!(rev->diffopt.file = fopen(filename.buf, "w"))) {
1118 error_errno(_("cannot open patch file %s"), filename.buf);
1119 strbuf_release(&filename);
1120 return -1;
1121 }
1122
1123 strbuf_release(&filename);
1124 return 0;
1125 }
1126
1127 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
1128 {
1129 struct rev_info check_rev;
1130 struct commit *commit, *c1, *c2;
1131 struct object *o1, *o2;
1132 unsigned flags1, flags2;
1133
1134 if (rev->pending.nr != 2)
1135 die(_("need exactly one range"));
1136
1137 o1 = rev->pending.objects[0].item;
1138 o2 = rev->pending.objects[1].item;
1139 flags1 = o1->flags;
1140 flags2 = o2->flags;
1141 c1 = lookup_commit_reference(the_repository, &o1->oid);
1142 c2 = lookup_commit_reference(the_repository, &o2->oid);
1143
1144 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1145 die(_("not a range"));
1146
1147 init_patch_ids(the_repository, ids);
1148
1149 /* given a range a..b get all patch ids for b..a */
1150 repo_init_revisions(the_repository, &check_rev, rev->prefix);
1151 check_rev.max_parents = 1;
1152 o1->flags ^= UNINTERESTING;
1153 o2->flags ^= UNINTERESTING;
1154 add_pending_object(&check_rev, o1, "o1");
1155 add_pending_object(&check_rev, o2, "o2");
1156 if (prepare_revision_walk(&check_rev))
1157 die(_("revision walk setup failed"));
1158
1159 while ((commit = get_revision(&check_rev)) != NULL) {
1160 add_commit_patch_id(commit, ids);
1161 }
1162
1163 /* reset for next revision walk */
1164 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1165 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1166 o1->flags = flags1;
1167 o2->flags = flags2;
1168 }
1169
1170 static void gen_message_id(struct rev_info *info, char *base)
1171 {
1172 struct strbuf buf = STRBUF_INIT;
1173 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1174 (timestamp_t) time(NULL),
1175 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1176 info->message_id = strbuf_detach(&buf, NULL);
1177 }
1178
1179 static void print_signature(FILE *file)
1180 {
1181 if (!signature || !*signature)
1182 return;
1183
1184 fprintf(file, "-- \n%s", signature);
1185 if (signature[strlen(signature)-1] != '\n')
1186 putc('\n', file);
1187 putc('\n', file);
1188 }
1189
1190 static char *find_branch_name(struct rev_info *rev)
1191 {
1192 int i, positive = -1;
1193 struct object_id branch_oid;
1194 const struct object_id *tip_oid;
1195 const char *ref, *v;
1196 char *full_ref, *branch = NULL;
1197
1198 for (i = 0; i < rev->cmdline.nr; i++) {
1199 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1200 continue;
1201 if (positive < 0)
1202 positive = i;
1203 else
1204 return NULL;
1205 }
1206 if (positive < 0)
1207 return NULL;
1208 ref = rev->cmdline.rev[positive].name;
1209 tip_oid = &rev->cmdline.rev[positive].item->oid;
1210 if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref, 0) &&
1211 skip_prefix(full_ref, "refs/heads/", &v) &&
1212 oideq(tip_oid, &branch_oid))
1213 branch = xstrdup(v);
1214 free(full_ref);
1215 return branch;
1216 }
1217
1218 static void show_diffstat(struct rev_info *rev,
1219 struct commit *origin, struct commit *head)
1220 {
1221 struct diff_options opts;
1222
1223 memcpy(&opts, &rev->diffopt, sizeof(opts));
1224 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1225 diff_setup_done(&opts);
1226
1227 diff_tree_oid(get_commit_tree_oid(origin),
1228 get_commit_tree_oid(head),
1229 "", &opts);
1230 diffcore_std(&opts);
1231 diff_flush(&opts);
1232
1233 fprintf(rev->diffopt.file, "\n");
1234 }
1235
1236 static void prepare_cover_text(struct pretty_print_context *pp,
1237 const char *branch_name,
1238 struct strbuf *sb,
1239 const char *encoding,
1240 int need_8bit_cte)
1241 {
1242 const char *subject = "*** SUBJECT HERE ***";
1243 const char *body = "*** BLURB HERE ***";
1244 struct strbuf description_sb = STRBUF_INIT;
1245 struct strbuf subject_sb = STRBUF_INIT;
1246
1247 if (cover_from_description_mode == COVER_FROM_NONE)
1248 goto do_pp;
1249
1250 if (branch_name && *branch_name)
1251 read_branch_desc(&description_sb, branch_name);
1252 if (!description_sb.len)
1253 goto do_pp;
1254
1255 if (cover_from_description_mode == COVER_FROM_SUBJECT ||
1256 cover_from_description_mode == COVER_FROM_AUTO)
1257 body = format_subject(&subject_sb, description_sb.buf, " ");
1258
1259 if (cover_from_description_mode == COVER_FROM_MESSAGE ||
1260 (cover_from_description_mode == COVER_FROM_AUTO &&
1261 subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1262 body = description_sb.buf;
1263 else
1264 subject = subject_sb.buf;
1265
1266 do_pp:
1267 pp_title_line(pp, &subject, sb, encoding, need_8bit_cte);
1268 pp_remainder(pp, &body, sb, 0);
1269
1270 strbuf_release(&description_sb);
1271 strbuf_release(&subject_sb);
1272 }
1273
1274 static int get_notes_refs(struct string_list_item *item, void *arg)
1275 {
1276 strvec_pushf(arg, "--notes=%s", item->string);
1277 return 0;
1278 }
1279
1280 static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1281 {
1282 if (!rev->show_notes) {
1283 strvec_push(arg, "--no-notes");
1284 } else if (rev->notes_opt.use_default_notes > 0 ||
1285 (rev->notes_opt.use_default_notes == -1 &&
1286 !rev->notes_opt.extra_notes_refs.nr)) {
1287 strvec_push(arg, "--notes");
1288 } else {
1289 for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1290 }
1291 }
1292
1293 static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1294 struct commit *origin,
1295 int nr, struct commit **list,
1296 const char *branch_name,
1297 int quiet)
1298 {
1299 const char *committer;
1300 struct shortlog log;
1301 struct strbuf sb = STRBUF_INIT;
1302 int i;
1303 const char *encoding = "UTF-8";
1304 int need_8bit_cte = 0;
1305 struct pretty_print_context pp = {0};
1306 struct commit *head = list[0];
1307
1308 if (!cmit_fmt_is_mail(rev->commit_format))
1309 die(_("cover letter needs email format"));
1310
1311 committer = git_committer_info(0);
1312
1313 if (use_separate_file &&
1314 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1315 die(_("failed to create cover-letter file"));
1316
1317 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1318
1319 for (i = 0; !need_8bit_cte && i < nr; i++) {
1320 const char *buf = get_commit_buffer(list[i], NULL);
1321 if (has_non_ascii(buf))
1322 need_8bit_cte = 1;
1323 unuse_commit_buffer(list[i], buf);
1324 }
1325
1326 if (!branch_name)
1327 branch_name = find_branch_name(rev);
1328
1329 pp.fmt = CMIT_FMT_EMAIL;
1330 pp.date_mode.type = DATE_RFC2822;
1331 pp.rev = rev;
1332 pp.print_email_subject = 1;
1333 pp_user_info(&pp, NULL, &sb, committer, encoding);
1334 prepare_cover_text(&pp, branch_name, &sb, encoding, need_8bit_cte);
1335 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1336
1337 strbuf_release(&sb);
1338
1339 shortlog_init(&log);
1340 log.wrap_lines = 1;
1341 log.wrap = MAIL_DEFAULT_WRAP;
1342 log.in1 = 2;
1343 log.in2 = 4;
1344 log.file = rev->diffopt.file;
1345 log.groups = SHORTLOG_GROUP_AUTHOR;
1346 shortlog_finish_setup(&log);
1347 for (i = 0; i < nr; i++)
1348 shortlog_add_commit(&log, list[i]);
1349
1350 shortlog_output(&log);
1351
1352 /* We can only do diffstat with a unique reference point */
1353 if (origin)
1354 show_diffstat(rev, origin, head);
1355
1356 if (rev->idiff_oid1) {
1357 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1358 show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1359 &rev->diffopt);
1360 }
1361
1362 if (rev->rdiff1) {
1363 /*
1364 * Pass minimum required diff-options to range-diff; others
1365 * can be added later if deemed desirable.
1366 */
1367 struct diff_options opts;
1368 struct strvec other_arg = STRVEC_INIT;
1369 struct range_diff_options range_diff_opts = {
1370 .creation_factor = rev->creation_factor,
1371 .dual_color = 1,
1372 .diffopt = &opts,
1373 .other_arg = &other_arg
1374 };
1375
1376 diff_setup(&opts);
1377 opts.file = rev->diffopt.file;
1378 opts.use_color = rev->diffopt.use_color;
1379 diff_setup_done(&opts);
1380 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1381 get_notes_args(&other_arg, rev);
1382 show_range_diff(rev->rdiff1, rev->rdiff2, &range_diff_opts);
1383 strvec_clear(&other_arg);
1384 }
1385 }
1386
1387 static const char *clean_message_id(const char *msg_id)
1388 {
1389 char ch;
1390 const char *a, *z, *m;
1391
1392 m = msg_id;
1393 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1394 m++;
1395 a = m;
1396 z = NULL;
1397 while ((ch = *m)) {
1398 if (!isspace(ch) && (ch != '>'))
1399 z = m;
1400 m++;
1401 }
1402 if (!z)
1403 die(_("insane in-reply-to: %s"), msg_id);
1404 if (++z == m)
1405 return a;
1406 return xmemdupz(a, z - a);
1407 }
1408
1409 static const char *set_outdir(const char *prefix, const char *output_directory)
1410 {
1411 if (output_directory && is_absolute_path(output_directory))
1412 return output_directory;
1413
1414 if (!prefix || !*prefix) {
1415 if (output_directory)
1416 return output_directory;
1417 /* The user did not explicitly ask for "./" */
1418 outdir_offset = 2;
1419 return "./";
1420 }
1421
1422 outdir_offset = strlen(prefix);
1423 if (!output_directory)
1424 return prefix;
1425
1426 return prefix_filename(prefix, output_directory);
1427 }
1428
1429 static const char * const builtin_format_patch_usage[] = {
1430 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1431 NULL
1432 };
1433
1434 static int keep_subject = 0;
1435
1436 static int keep_callback(const struct option *opt, const char *arg, int unset)
1437 {
1438 BUG_ON_OPT_NEG(unset);
1439 BUG_ON_OPT_ARG(arg);
1440 ((struct rev_info *)opt->value)->total = -1;
1441 keep_subject = 1;
1442 return 0;
1443 }
1444
1445 static int subject_prefix = 0;
1446
1447 static int subject_prefix_callback(const struct option *opt, const char *arg,
1448 int unset)
1449 {
1450 BUG_ON_OPT_NEG(unset);
1451 subject_prefix = 1;
1452 ((struct rev_info *)opt->value)->subject_prefix = arg;
1453 return 0;
1454 }
1455
1456 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1457 {
1458 BUG_ON_OPT_NEG(unset);
1459 BUG_ON_OPT_ARG(arg);
1460 return subject_prefix_callback(opt, "RFC PATCH", unset);
1461 }
1462
1463 static int numbered_cmdline_opt = 0;
1464
1465 static int numbered_callback(const struct option *opt, const char *arg,
1466 int unset)
1467 {
1468 BUG_ON_OPT_ARG(arg);
1469 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1470 if (unset)
1471 auto_number = 0;
1472 return 0;
1473 }
1474
1475 static int no_numbered_callback(const struct option *opt, const char *arg,
1476 int unset)
1477 {
1478 BUG_ON_OPT_NEG(unset);
1479 return numbered_callback(opt, arg, 1);
1480 }
1481
1482 static int output_directory_callback(const struct option *opt, const char *arg,
1483 int unset)
1484 {
1485 const char **dir = (const char **)opt->value;
1486 BUG_ON_OPT_NEG(unset);
1487 if (*dir)
1488 die(_("two output directories?"));
1489 *dir = arg;
1490 return 0;
1491 }
1492
1493 static int thread_callback(const struct option *opt, const char *arg, int unset)
1494 {
1495 enum thread_level *thread = (enum thread_level *)opt->value;
1496 if (unset)
1497 *thread = THREAD_UNSET;
1498 else if (!arg || !strcmp(arg, "shallow"))
1499 *thread = THREAD_SHALLOW;
1500 else if (!strcmp(arg, "deep"))
1501 *thread = THREAD_DEEP;
1502 /*
1503 * Please update _git_formatpatch() in git-completion.bash
1504 * when you add new options.
1505 */
1506 else
1507 return 1;
1508 return 0;
1509 }
1510
1511 static int attach_callback(const struct option *opt, const char *arg, int unset)
1512 {
1513 struct rev_info *rev = (struct rev_info *)opt->value;
1514 if (unset)
1515 rev->mime_boundary = NULL;
1516 else if (arg)
1517 rev->mime_boundary = arg;
1518 else
1519 rev->mime_boundary = git_version_string;
1520 rev->no_inline = unset ? 0 : 1;
1521 return 0;
1522 }
1523
1524 static int inline_callback(const struct option *opt, const char *arg, int unset)
1525 {
1526 struct rev_info *rev = (struct rev_info *)opt->value;
1527 if (unset)
1528 rev->mime_boundary = NULL;
1529 else if (arg)
1530 rev->mime_boundary = arg;
1531 else
1532 rev->mime_boundary = git_version_string;
1533 rev->no_inline = 0;
1534 return 0;
1535 }
1536
1537 static int header_callback(const struct option *opt, const char *arg, int unset)
1538 {
1539 if (unset) {
1540 string_list_clear(&extra_hdr, 0);
1541 string_list_clear(&extra_to, 0);
1542 string_list_clear(&extra_cc, 0);
1543 } else {
1544 add_header(arg);
1545 }
1546 return 0;
1547 }
1548
1549 static int to_callback(const struct option *opt, const char *arg, int unset)
1550 {
1551 if (unset)
1552 string_list_clear(&extra_to, 0);
1553 else
1554 string_list_append(&extra_to, arg);
1555 return 0;
1556 }
1557
1558 static int cc_callback(const struct option *opt, const char *arg, int unset)
1559 {
1560 if (unset)
1561 string_list_clear(&extra_cc, 0);
1562 else
1563 string_list_append(&extra_cc, arg);
1564 return 0;
1565 }
1566
1567 static int from_callback(const struct option *opt, const char *arg, int unset)
1568 {
1569 char **from = opt->value;
1570
1571 free(*from);
1572
1573 if (unset)
1574 *from = NULL;
1575 else if (arg)
1576 *from = xstrdup(arg);
1577 else
1578 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1579 return 0;
1580 }
1581
1582 static int base_callback(const struct option *opt, const char *arg, int unset)
1583 {
1584 const char **base_commit = opt->value;
1585
1586 if (unset) {
1587 auto_base = AUTO_BASE_NEVER;
1588 *base_commit = NULL;
1589 } else if (!strcmp(arg, "auto")) {
1590 auto_base = AUTO_BASE_ALWAYS;
1591 *base_commit = NULL;
1592 } else {
1593 auto_base = AUTO_BASE_NEVER;
1594 *base_commit = arg;
1595 }
1596 return 0;
1597 }
1598
1599 struct base_tree_info {
1600 struct object_id base_commit;
1601 int nr_patch_id, alloc_patch_id;
1602 struct object_id *patch_id;
1603 };
1604
1605 static struct commit *get_base_commit(const char *base_commit,
1606 struct commit **list,
1607 int total)
1608 {
1609 struct commit *base = NULL;
1610 struct commit **rev;
1611 int i = 0, rev_nr = 0, auto_select, die_on_failure;
1612
1613 switch (auto_base) {
1614 case AUTO_BASE_NEVER:
1615 if (base_commit) {
1616 auto_select = 0;
1617 die_on_failure = 1;
1618 } else {
1619 /* no base information is requested */
1620 return NULL;
1621 }
1622 break;
1623 case AUTO_BASE_ALWAYS:
1624 case AUTO_BASE_WHEN_ABLE:
1625 if (base_commit) {
1626 BUG("requested automatic base selection but a commit was provided");
1627 } else {
1628 auto_select = 1;
1629 die_on_failure = auto_base == AUTO_BASE_ALWAYS;
1630 }
1631 break;
1632 default:
1633 BUG("unexpected automatic base selection method");
1634 }
1635
1636 if (!auto_select) {
1637 base = lookup_commit_reference_by_name(base_commit);
1638 if (!base)
1639 die(_("unknown commit %s"), base_commit);
1640 } else {
1641 struct branch *curr_branch = branch_get(NULL);
1642 const char *upstream = branch_get_upstream(curr_branch, NULL);
1643 if (upstream) {
1644 struct commit_list *base_list;
1645 struct commit *commit;
1646 struct object_id oid;
1647
1648 if (get_oid(upstream, &oid)) {
1649 if (die_on_failure)
1650 die(_("failed to resolve '%s' as a valid ref"), upstream);
1651 else
1652 return NULL;
1653 }
1654 commit = lookup_commit_or_die(&oid, "upstream base");
1655 base_list = get_merge_bases_many(commit, total, list);
1656 /* There should be one and only one merge base. */
1657 if (!base_list || base_list->next) {
1658 if (die_on_failure) {
1659 die(_("could not find exact merge base"));
1660 } else {
1661 free_commit_list(base_list);
1662 return NULL;
1663 }
1664 }
1665 base = base_list->item;
1666 free_commit_list(base_list);
1667 } else {
1668 if (die_on_failure)
1669 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1670 "please use git branch --set-upstream-to to track a remote branch.\n"
1671 "Or you could specify base commit by --base=<base-commit-id> manually"));
1672 else
1673 return NULL;
1674 }
1675 }
1676
1677 ALLOC_ARRAY(rev, total);
1678 for (i = 0; i < total; i++)
1679 rev[i] = list[i];
1680
1681 rev_nr = total;
1682 /*
1683 * Get merge base through pair-wise computations
1684 * and store it in rev[0].
1685 */
1686 while (rev_nr > 1) {
1687 for (i = 0; i < rev_nr / 2; i++) {
1688 struct commit_list *merge_base;
1689 merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1690 if (!merge_base || merge_base->next) {
1691 if (die_on_failure) {
1692 die(_("failed to find exact merge base"));
1693 } else {
1694 free(rev);
1695 return NULL;
1696 }
1697 }
1698
1699 rev[i] = merge_base->item;
1700 }
1701
1702 if (rev_nr % 2)
1703 rev[i] = rev[2 * i];
1704 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1705 }
1706
1707 if (!in_merge_bases(base, rev[0])) {
1708 if (die_on_failure) {
1709 die(_("base commit should be the ancestor of revision list"));
1710 } else {
1711 free(rev);
1712 return NULL;
1713 }
1714 }
1715
1716 for (i = 0; i < total; i++) {
1717 if (base == list[i]) {
1718 if (die_on_failure) {
1719 die(_("base commit shouldn't be in revision list"));
1720 } else {
1721 free(rev);
1722 return NULL;
1723 }
1724 }
1725 }
1726
1727 free(rev);
1728 return base;
1729 }
1730
1731 define_commit_slab(commit_base, int);
1732
1733 static void prepare_bases(struct base_tree_info *bases,
1734 struct commit *base,
1735 struct commit **list,
1736 int total)
1737 {
1738 struct commit *commit;
1739 struct rev_info revs;
1740 struct diff_options diffopt;
1741 struct commit_base commit_base;
1742 int i;
1743
1744 if (!base)
1745 return;
1746
1747 init_commit_base(&commit_base);
1748 repo_diff_setup(the_repository, &diffopt);
1749 diffopt.flags.recursive = 1;
1750 diff_setup_done(&diffopt);
1751
1752 oidcpy(&bases->base_commit, &base->object.oid);
1753
1754 repo_init_revisions(the_repository, &revs, NULL);
1755 revs.max_parents = 1;
1756 revs.topo_order = 1;
1757 for (i = 0; i < total; i++) {
1758 list[i]->object.flags &= ~UNINTERESTING;
1759 add_pending_object(&revs, &list[i]->object, "rev_list");
1760 *commit_base_at(&commit_base, list[i]) = 1;
1761 }
1762 base->object.flags |= UNINTERESTING;
1763 add_pending_object(&revs, &base->object, "base");
1764
1765 if (prepare_revision_walk(&revs))
1766 die(_("revision walk setup failed"));
1767 /*
1768 * Traverse the commits list, get prerequisite patch ids
1769 * and stuff them in bases structure.
1770 */
1771 while ((commit = get_revision(&revs)) != NULL) {
1772 struct object_id oid;
1773 struct object_id *patch_id;
1774 if (*commit_base_at(&commit_base, commit))
1775 continue;
1776 if (commit_patch_id(commit, &diffopt, &oid, 0))
1777 die(_("cannot get patch id"));
1778 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1779 patch_id = bases->patch_id + bases->nr_patch_id;
1780 oidcpy(patch_id, &oid);
1781 bases->nr_patch_id++;
1782 }
1783 clear_commit_base(&commit_base);
1784 }
1785
1786 static void print_bases(struct base_tree_info *bases, FILE *file)
1787 {
1788 int i;
1789
1790 /* Only do this once, either for the cover or for the first one */
1791 if (is_null_oid(&bases->base_commit))
1792 return;
1793
1794 /* Show the base commit */
1795 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1796
1797 /* Show the prerequisite patches */
1798 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1799 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1800
1801 free(bases->patch_id);
1802 bases->nr_patch_id = 0;
1803 bases->alloc_patch_id = 0;
1804 oidclr(&bases->base_commit);
1805 }
1806
1807 static const char *diff_title(struct strbuf *sb,
1808 const char *reroll_count,
1809 const char *generic,
1810 const char *rerolled)
1811 {
1812 int v;
1813
1814 /* RFC may be v0, so allow -v1 to diff against v0 */
1815 if (reroll_count && !strtol_i(reroll_count, 10, &v) &&
1816 v >= 1)
1817 strbuf_addf(sb, rerolled, v - 1);
1818 else
1819 strbuf_addstr(sb, generic);
1820 return sb->buf;
1821 }
1822
1823 static void infer_range_diff_ranges(struct strbuf *r1,
1824 struct strbuf *r2,
1825 const char *prev,
1826 struct commit *origin,
1827 struct commit *head)
1828 {
1829 const char *head_oid = oid_to_hex(&head->object.oid);
1830 int prev_is_range = is_range_diff_range(prev);
1831
1832 if (prev_is_range)
1833 strbuf_addstr(r1, prev);
1834 else
1835 strbuf_addf(r1, "%s..%s", head_oid, prev);
1836
1837 if (origin)
1838 strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1839 else if (prev_is_range)
1840 die(_("failed to infer range-diff origin of current series"));
1841 else {
1842 warning(_("using '%s' as range-diff origin of current series"), prev);
1843 strbuf_addf(r2, "%s..%s", prev, head_oid);
1844 }
1845 }
1846
1847 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1848 {
1849 struct commit *commit;
1850 struct commit **list = NULL;
1851 struct rev_info rev;
1852 char *to_free = NULL;
1853 struct setup_revision_opt s_r_opt;
1854 int nr = 0, total, i;
1855 int use_stdout = 0;
1856 int start_number = -1;
1857 int just_numbers = 0;
1858 int ignore_if_in_upstream = 0;
1859 int cover_letter = -1;
1860 int boundary_count = 0;
1861 int no_binary_diff = 0;
1862 int zero_commit = 0;
1863 struct commit *origin = NULL;
1864 const char *in_reply_to = NULL;
1865 struct patch_ids ids;
1866 struct strbuf buf = STRBUF_INIT;
1867 int use_patch_format = 0;
1868 int quiet = 0;
1869 const char *reroll_count = NULL;
1870 char *cover_from_description_arg = NULL;
1871 char *branch_name = NULL;
1872 char *base_commit = NULL;
1873 struct base_tree_info bases;
1874 struct commit *base;
1875 int show_progress = 0;
1876 struct progress *progress = NULL;
1877 struct oid_array idiff_prev = OID_ARRAY_INIT;
1878 struct strbuf idiff_title = STRBUF_INIT;
1879 const char *rdiff_prev = NULL;
1880 struct strbuf rdiff1 = STRBUF_INIT;
1881 struct strbuf rdiff2 = STRBUF_INIT;
1882 struct strbuf rdiff_title = STRBUF_INIT;
1883 struct strbuf sprefix = STRBUF_INIT;
1884 int creation_factor = -1;
1885
1886 const struct option builtin_format_patch_options[] = {
1887 OPT_CALLBACK_F('n', "numbered", &numbered, NULL,
1888 N_("use [PATCH n/m] even with a single patch"),
1889 PARSE_OPT_NOARG, numbered_callback),
1890 OPT_CALLBACK_F('N', "no-numbered", &numbered, NULL,
1891 N_("use [PATCH] even with multiple patches"),
1892 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
1893 OPT_BOOL('s', "signoff", &do_signoff, N_("add a Signed-off-by trailer")),
1894 OPT_BOOL(0, "stdout", &use_stdout,
1895 N_("print patches to standard out")),
1896 OPT_BOOL(0, "cover-letter", &cover_letter,
1897 N_("generate a cover letter")),
1898 OPT_BOOL(0, "numbered-files", &just_numbers,
1899 N_("use simple number sequence for output file names")),
1900 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1901 N_("use <sfx> instead of '.patch'")),
1902 OPT_INTEGER(0, "start-number", &start_number,
1903 N_("start numbering patches at <n> instead of 1")),
1904 OPT_STRING('v', "reroll-count", &reroll_count, N_("reroll-count"),
1905 N_("mark the series as Nth re-roll")),
1906 OPT_INTEGER(0, "filename-max-length", &fmt_patch_name_max,
1907 N_("max length of output filename")),
1908 OPT_CALLBACK_F(0, "rfc", &rev, NULL,
1909 N_("use [RFC PATCH] instead of [PATCH]"),
1910 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback),
1911 OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
1912 N_("cover-from-description-mode"),
1913 N_("generate parts of a cover letter based on a branch's description")),
1914 OPT_CALLBACK_F(0, "subject-prefix", &rev, N_("prefix"),
1915 N_("use [<prefix>] instead of [PATCH]"),
1916 PARSE_OPT_NONEG, subject_prefix_callback),
1917 OPT_CALLBACK_F('o', "output-directory", &output_directory,
1918 N_("dir"), N_("store resulting files in <dir>"),
1919 PARSE_OPT_NONEG, output_directory_callback),
1920 OPT_CALLBACK_F('k', "keep-subject", &rev, NULL,
1921 N_("don't strip/add [PATCH]"),
1922 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
1923 OPT_BOOL(0, "no-binary", &no_binary_diff,
1924 N_("don't output binary diffs")),
1925 OPT_BOOL(0, "zero-commit", &zero_commit,
1926 N_("output all-zero hash in From header")),
1927 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1928 N_("don't include a patch matching a commit upstream")),
1929 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1930 N_("show patch format instead of default (patch + stat)"),
1931 1, PARSE_OPT_NONEG),
1932 OPT_GROUP(N_("Messaging")),
1933 OPT_CALLBACK(0, "add-header", NULL, N_("header"),
1934 N_("add email header"), header_callback),
1935 OPT_CALLBACK(0, "to", NULL, N_("email"), N_("add To: header"), to_callback),
1936 OPT_CALLBACK(0, "cc", NULL, N_("email"), N_("add Cc: header"), cc_callback),
1937 OPT_CALLBACK_F(0, "from", &from, N_("ident"),
1938 N_("set From address to <ident> (or committer ident if absent)"),
1939 PARSE_OPT_OPTARG, from_callback),
1940 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1941 N_("make first mail a reply to <message-id>")),
1942 OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
1943 N_("attach the patch"), PARSE_OPT_OPTARG,
1944 attach_callback),
1945 OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
1946 N_("inline the patch"),
1947 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1948 inline_callback),
1949 OPT_CALLBACK_F(0, "thread", &thread, N_("style"),
1950 N_("enable message threading, styles: shallow, deep"),
1951 PARSE_OPT_OPTARG, thread_callback),
1952 OPT_STRING(0, "signature", &signature, N_("signature"),
1953 N_("add a signature")),
1954 OPT_CALLBACK_F(0, "base", &base_commit, N_("base-commit"),
1955 N_("add prerequisite tree info to the patch series"),
1956 0, base_callback),
1957 OPT_FILENAME(0, "signature-file", &signature_file,
1958 N_("add a signature from a file")),
1959 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1960 OPT_BOOL(0, "progress", &show_progress,
1961 N_("show progress while generating patches")),
1962 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1963 N_("show changes against <rev> in cover letter or single patch"),
1964 parse_opt_object_name),
1965 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1966 N_("show changes against <refspec> in cover letter or single patch")),
1967 OPT_INTEGER(0, "creation-factor", &creation_factor,
1968 N_("percentage by which creation is weighted")),
1969 OPT_BOOL(0, "force-in-body-from", &force_in_body_from,
1970 N_("show in-body From: even if identical to the e-mail header")),
1971 OPT_END()
1972 };
1973
1974 extra_hdr.strdup_strings = 1;
1975 extra_to.strdup_strings = 1;
1976 extra_cc.strdup_strings = 1;
1977
1978 init_log_defaults();
1979 init_display_notes(&notes_opt);
1980 git_config(git_format_config, NULL);
1981 repo_init_revisions(the_repository, &rev, prefix);
1982 git_config(grep_config, &rev.grep_filter);
1983
1984 rev.show_notes = show_notes;
1985 memcpy(&rev.notes_opt, &notes_opt, sizeof(notes_opt));
1986 rev.commit_format = CMIT_FMT_EMAIL;
1987 rev.encode_email_headers = default_encode_email_headers;
1988 rev.expand_tabs_in_log_default = 0;
1989 rev.verbose_header = 1;
1990 rev.diff = 1;
1991 rev.max_parents = 1;
1992 rev.diffopt.flags.recursive = 1;
1993 rev.diffopt.no_free = 1;
1994 rev.subject_prefix = fmt_patch_subject_prefix;
1995 memset(&s_r_opt, 0, sizeof(s_r_opt));
1996 s_r_opt.def = "HEAD";
1997 s_r_opt.revarg_opt = REVARG_COMMITTISH;
1998
1999 if (default_attach) {
2000 rev.mime_boundary = default_attach;
2001 rev.no_inline = 1;
2002 }
2003
2004 /*
2005 * Parse the arguments before setup_revisions(), or something
2006 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
2007 * possibly a valid SHA1.
2008 */
2009 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
2010 builtin_format_patch_usage,
2011 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
2012 PARSE_OPT_KEEP_DASHDASH);
2013
2014 rev.force_in_body_from = force_in_body_from;
2015
2016 /* Make sure "0000-$sub.patch" gives non-negative length for $sub */
2017 if (fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
2018 fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
2019
2020 if (cover_from_description_arg)
2021 cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
2022
2023 if (reroll_count) {
2024 strbuf_addf(&sprefix, "%s v%s",
2025 rev.subject_prefix, reroll_count);
2026 rev.reroll_count = reroll_count;
2027 rev.subject_prefix = sprefix.buf;
2028 }
2029
2030 for (i = 0; i < extra_hdr.nr; i++) {
2031 strbuf_addstr(&buf, extra_hdr.items[i].string);
2032 strbuf_addch(&buf, '\n');
2033 }
2034
2035 if (extra_to.nr)
2036 strbuf_addstr(&buf, "To: ");
2037 for (i = 0; i < extra_to.nr; i++) {
2038 if (i)
2039 strbuf_addstr(&buf, " ");
2040 strbuf_addstr(&buf, extra_to.items[i].string);
2041 if (i + 1 < extra_to.nr)
2042 strbuf_addch(&buf, ',');
2043 strbuf_addch(&buf, '\n');
2044 }
2045
2046 if (extra_cc.nr)
2047 strbuf_addstr(&buf, "Cc: ");
2048 for (i = 0; i < extra_cc.nr; i++) {
2049 if (i)
2050 strbuf_addstr(&buf, " ");
2051 strbuf_addstr(&buf, extra_cc.items[i].string);
2052 if (i + 1 < extra_cc.nr)
2053 strbuf_addch(&buf, ',');
2054 strbuf_addch(&buf, '\n');
2055 }
2056
2057 rev.extra_headers = to_free = strbuf_detach(&buf, NULL);
2058
2059 if (from) {
2060 if (split_ident_line(&rev.from_ident, from, strlen(from)))
2061 die(_("invalid ident line: %s"), from);
2062 }
2063
2064 if (start_number < 0)
2065 start_number = 1;
2066
2067 /*
2068 * If numbered is set solely due to format.numbered in config,
2069 * and it would conflict with --keep-subject (-k) from the
2070 * command line, reset "numbered".
2071 */
2072 if (numbered && keep_subject && !numbered_cmdline_opt)
2073 numbered = 0;
2074
2075 if (numbered && keep_subject)
2076 die(_("options '%s' and '%s' cannot be used together"), "-n", "-k");
2077 if (keep_subject && subject_prefix)
2078 die(_("options '%s' and '%s' cannot be used together"), "--subject-prefix/--rfc", "-k");
2079 rev.preserve_subject = keep_subject;
2080
2081 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
2082 if (argc > 1)
2083 die(_("unrecognized argument: %s"), argv[1]);
2084
2085 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
2086 die(_("--name-only does not make sense"));
2087 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
2088 die(_("--name-status does not make sense"));
2089 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
2090 die(_("--check does not make sense"));
2091 if (rev.remerge_diff)
2092 die(_("--remerge-diff does not make sense"));
2093
2094 if (!use_patch_format &&
2095 (!rev.diffopt.output_format ||
2096 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
2097 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
2098 if (!rev.diffopt.stat_width)
2099 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
2100
2101 /* Always generate a patch */
2102 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
2103 rev.always_show_header = 1;
2104
2105 rev.zero_commit = zero_commit;
2106 rev.patch_name_max = fmt_patch_name_max;
2107
2108 if (!rev.diffopt.flags.text && !no_binary_diff)
2109 rev.diffopt.flags.binary = 1;
2110
2111 if (rev.show_notes)
2112 load_display_notes(&rev.notes_opt);
2113
2114 die_for_incompatible_opt3(use_stdout, "--stdout",
2115 rev.diffopt.close_file, "--output",
2116 !!output_directory, "--output-directory");
2117
2118 if (use_stdout && stdout_mboxrd)
2119 rev.commit_format = CMIT_FMT_MBOXRD;
2120
2121 if (use_stdout) {
2122 setup_pager();
2123 } else if (!rev.diffopt.close_file) {
2124 int saved;
2125
2126 if (!output_directory)
2127 output_directory = config_output_directory;
2128 output_directory = set_outdir(prefix, output_directory);
2129
2130 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
2131 rev.diffopt.use_color = GIT_COLOR_NEVER;
2132 /*
2133 * We consider <outdir> as 'outside of gitdir', therefore avoid
2134 * applying adjust_shared_perm in s-c-l-d.
2135 */
2136 saved = get_shared_repository();
2137 set_shared_repository(0);
2138 switch (safe_create_leading_directories_const(output_directory)) {
2139 case SCLD_OK:
2140 case SCLD_EXISTS:
2141 break;
2142 default:
2143 die(_("could not create leading directories "
2144 "of '%s'"), output_directory);
2145 }
2146 set_shared_repository(saved);
2147 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
2148 die_errno(_("could not create directory '%s'"),
2149 output_directory);
2150 }
2151
2152 if (rev.pending.nr == 1) {
2153 int check_head = 0;
2154
2155 if (rev.max_count < 0 && !rev.show_root_diff) {
2156 /*
2157 * This is traditional behaviour of "git format-patch
2158 * origin" that prepares what the origin side still
2159 * does not have.
2160 */
2161 rev.pending.objects[0].item->flags |= UNINTERESTING;
2162 add_head_to_pending(&rev);
2163 check_head = 1;
2164 }
2165 /*
2166 * Otherwise, it is "format-patch -22 HEAD", and/or
2167 * "format-patch --root HEAD". The user wants
2168 * get_revision() to do the usual traversal.
2169 */
2170
2171 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
2172 check_head = 1;
2173
2174 if (check_head) {
2175 const char *ref, *v;
2176 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2177 NULL, NULL);
2178 if (ref && skip_prefix(ref, "refs/heads/", &v))
2179 branch_name = xstrdup(v);
2180 else
2181 branch_name = xstrdup(""); /* no branch */
2182 }
2183 }
2184
2185 /*
2186 * We cannot move this anywhere earlier because we do want to
2187 * know if --root was given explicitly from the command line.
2188 */
2189 rev.show_root_diff = 1;
2190
2191 if (ignore_if_in_upstream) {
2192 /* Don't say anything if head and upstream are the same. */
2193 if (rev.pending.nr == 2) {
2194 struct object_array_entry *o = rev.pending.objects;
2195 if (oideq(&o[0].item->oid, &o[1].item->oid))
2196 goto done;
2197 }
2198 get_patch_ids(&rev, &ids);
2199 }
2200
2201 if (prepare_revision_walk(&rev))
2202 die(_("revision walk setup failed"));
2203 rev.boundary = 1;
2204 while ((commit = get_revision(&rev)) != NULL) {
2205 if (commit->object.flags & BOUNDARY) {
2206 boundary_count++;
2207 origin = (boundary_count == 1) ? commit : NULL;
2208 continue;
2209 }
2210
2211 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2212 continue;
2213
2214 nr++;
2215 REALLOC_ARRAY(list, nr);
2216 list[nr - 1] = commit;
2217 }
2218 if (nr == 0)
2219 /* nothing to do */
2220 goto done;
2221 total = nr;
2222 if (cover_letter == -1) {
2223 if (config_cover_letter == COVER_AUTO)
2224 cover_letter = (total > 1);
2225 else
2226 cover_letter = (config_cover_letter == COVER_ON);
2227 }
2228 if (!keep_subject && auto_number && (total > 1 || cover_letter))
2229 numbered = 1;
2230 if (numbered)
2231 rev.total = total + start_number - 1;
2232
2233 if (idiff_prev.nr) {
2234 if (!cover_letter && total != 1)
2235 die(_("--interdiff requires --cover-letter or single patch"));
2236 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2237 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2238 rev.idiff_title = diff_title(&idiff_title, reroll_count,
2239 _("Interdiff:"),
2240 _("Interdiff against v%d:"));
2241 }
2242
2243 if (creation_factor < 0)
2244 creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
2245 else if (!rdiff_prev)
2246 die(_("the option '%s' requires '%s'"), "--creation-factor", "--range-diff");
2247
2248 if (rdiff_prev) {
2249 if (!cover_letter && total != 1)
2250 die(_("--range-diff requires --cover-letter or single patch"));
2251
2252 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2253 origin, list[0]);
2254 rev.rdiff1 = rdiff1.buf;
2255 rev.rdiff2 = rdiff2.buf;
2256 rev.creation_factor = creation_factor;
2257 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2258 _("Range-diff:"),
2259 _("Range-diff against v%d:"));
2260 }
2261
2262 if (!signature) {
2263 ; /* --no-signature inhibits all signatures */
2264 } else if (signature && signature != git_version_string) {
2265 ; /* non-default signature already set */
2266 } else if (signature_file) {
2267 struct strbuf buf = STRBUF_INIT;
2268
2269 if (strbuf_read_file(&buf, signature_file, 128) < 0)
2270 die_errno(_("unable to read signature file '%s'"), signature_file);
2271 signature = strbuf_detach(&buf, NULL);
2272 }
2273
2274 memset(&bases, 0, sizeof(bases));
2275 base = get_base_commit(base_commit, list, nr);
2276 if (base) {
2277 reset_revision_walk();
2278 clear_object_flags(UNINTERESTING);
2279 prepare_bases(&bases, base, list, nr);
2280 }
2281
2282 if (in_reply_to || thread || cover_letter) {
2283 rev.ref_message_ids = xmalloc(sizeof(*rev.ref_message_ids));
2284 string_list_init_nodup(rev.ref_message_ids);
2285 }
2286 if (in_reply_to) {
2287 const char *msgid = clean_message_id(in_reply_to);
2288 string_list_append(rev.ref_message_ids, msgid);
2289 }
2290 rev.numbered_files = just_numbers;
2291 rev.patch_suffix = fmt_patch_suffix;
2292 if (cover_letter) {
2293 if (thread)
2294 gen_message_id(&rev, "cover");
2295 make_cover_letter(&rev, !!output_directory,
2296 origin, nr, list, branch_name, quiet);
2297 print_bases(&bases, rev.diffopt.file);
2298 print_signature(rev.diffopt.file);
2299 total++;
2300 start_number--;
2301 /* interdiff/range-diff in cover-letter; omit from patches */
2302 rev.idiff_oid1 = NULL;
2303 rev.rdiff1 = NULL;
2304 }
2305 rev.add_signoff = do_signoff;
2306
2307 if (show_progress)
2308 progress = start_delayed_progress(_("Generating patches"), total);
2309 while (0 <= --nr) {
2310 int shown;
2311 display_progress(progress, total - nr);
2312 commit = list[nr];
2313 rev.nr = total - nr + (start_number - 1);
2314 /* Make the second and subsequent mails replies to the first */
2315 if (thread) {
2316 /* Have we already had a message ID? */
2317 if (rev.message_id) {
2318 /*
2319 * For deep threading: make every mail
2320 * a reply to the previous one, no
2321 * matter what other options are set.
2322 *
2323 * For shallow threading:
2324 *
2325 * Without --cover-letter and
2326 * --in-reply-to, make every mail a
2327 * reply to the one before.
2328 *
2329 * With --in-reply-to but no
2330 * --cover-letter, make every mail a
2331 * reply to the <reply-to>.
2332 *
2333 * With --cover-letter, make every
2334 * mail but the cover letter a reply
2335 * to the cover letter. The cover
2336 * letter is a reply to the
2337 * --in-reply-to, if specified.
2338 */
2339 if (thread == THREAD_SHALLOW
2340 && rev.ref_message_ids->nr > 0
2341 && (!cover_letter || rev.nr > 1))
2342 free(rev.message_id);
2343 else
2344 string_list_append(rev.ref_message_ids,
2345 rev.message_id);
2346 }
2347 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2348 }
2349
2350 if (output_directory &&
2351 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2352 die(_("failed to create output files"));
2353 shown = log_tree_commit(&rev, commit);
2354 free_commit_buffer(the_repository->parsed_objects,
2355 commit);
2356
2357 /* We put one extra blank line between formatted
2358 * patches and this flag is used by log-tree code
2359 * to see if it needs to emit a LF before showing
2360 * the log; when using one file per patch, we do
2361 * not want the extra blank line.
2362 */
2363 if (output_directory)
2364 rev.shown_one = 0;
2365 if (shown) {
2366 print_bases(&bases, rev.diffopt.file);
2367 if (rev.mime_boundary)
2368 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2369 mime_boundary_leader,
2370 rev.mime_boundary);
2371 else
2372 print_signature(rev.diffopt.file);
2373 }
2374 if (output_directory)
2375 fclose(rev.diffopt.file);
2376 }
2377 stop_progress(&progress);
2378 free(list);
2379 free(branch_name);
2380 string_list_clear(&extra_to, 0);
2381 string_list_clear(&extra_cc, 0);
2382 string_list_clear(&extra_hdr, 0);
2383 if (ignore_if_in_upstream)
2384 free_patch_ids(&ids);
2385
2386 done:
2387 oid_array_clear(&idiff_prev);
2388 strbuf_release(&idiff_title);
2389 strbuf_release(&rdiff1);
2390 strbuf_release(&rdiff2);
2391 strbuf_release(&rdiff_title);
2392 strbuf_release(&sprefix);
2393 free(to_free);
2394 if (rev.ref_message_ids)
2395 string_list_clear(rev.ref_message_ids, 0);
2396 free(rev.ref_message_ids);
2397 return cmd_log_deinit(0, &rev);
2398 }
2399
2400 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2401 {
2402 struct object_id oid;
2403 if (get_oid(arg, &oid) == 0) {
2404 struct commit *commit = lookup_commit_reference(the_repository,
2405 &oid);
2406 if (commit) {
2407 commit->object.flags |= flags;
2408 add_pending_object(revs, &commit->object, arg);
2409 return 0;
2410 }
2411 }
2412 return -1;
2413 }
2414
2415 static const char * const cherry_usage[] = {
2416 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2417 NULL
2418 };
2419
2420 static void print_commit(char sign, struct commit *commit, int verbose,
2421 int abbrev, FILE *file)
2422 {
2423 if (!verbose) {
2424 fprintf(file, "%c %s\n", sign,
2425 find_unique_abbrev(&commit->object.oid, abbrev));
2426 } else {
2427 struct strbuf buf = STRBUF_INIT;
2428 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2429 fprintf(file, "%c %s %s\n", sign,
2430 find_unique_abbrev(&commit->object.oid, abbrev),
2431 buf.buf);
2432 strbuf_release(&buf);
2433 }
2434 }
2435
2436 int cmd_cherry(int argc, const char **argv, const char *prefix)
2437 {
2438 struct rev_info revs;
2439 struct patch_ids ids;
2440 struct commit *commit;
2441 struct commit_list *list = NULL;
2442 struct branch *current_branch;
2443 const char *upstream;
2444 const char *head = "HEAD";
2445 const char *limit = NULL;
2446 int verbose = 0, abbrev = 0;
2447
2448 struct option options[] = {
2449 OPT__ABBREV(&abbrev),
2450 OPT__VERBOSE(&verbose, N_("be verbose")),
2451 OPT_END()
2452 };
2453
2454 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2455
2456 switch (argc) {
2457 case 3:
2458 limit = argv[2];
2459 /* FALLTHROUGH */
2460 case 2:
2461 head = argv[1];
2462 /* FALLTHROUGH */
2463 case 1:
2464 upstream = argv[0];
2465 break;
2466 default:
2467 current_branch = branch_get(NULL);
2468 upstream = branch_get_upstream(current_branch, NULL);
2469 if (!upstream) {
2470 fprintf(stderr, _("Could not find a tracked"
2471 " remote branch, please"
2472 " specify <upstream> manually.\n"));
2473 usage_with_options(cherry_usage, options);
2474 }
2475 }
2476
2477 repo_init_revisions(the_repository, &revs, prefix);
2478 revs.max_parents = 1;
2479
2480 if (add_pending_commit(head, &revs, 0))
2481 die(_("unknown commit %s"), head);
2482 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2483 die(_("unknown commit %s"), upstream);
2484
2485 /* Don't say anything if head and upstream are the same. */
2486 if (revs.pending.nr == 2) {
2487 struct object_array_entry *o = revs.pending.objects;
2488 if (oideq(&o[0].item->oid, &o[1].item->oid))
2489 return 0;
2490 }
2491
2492 get_patch_ids(&revs, &ids);
2493
2494 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2495 die(_("unknown commit %s"), limit);
2496
2497 /* reverse the list of commits */
2498 if (prepare_revision_walk(&revs))
2499 die(_("revision walk setup failed"));
2500 while ((commit = get_revision(&revs)) != NULL) {
2501 commit_list_insert(commit, &list);
2502 }
2503
2504 while (list) {
2505 char sign = '+';
2506
2507 commit = list->item;
2508 if (has_commit_patch_id(commit, &ids))
2509 sign = '-';
2510 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2511 list = list->next;
2512 }
2513
2514 free_patch_ids(&ids);
2515 return 0;
2516 }