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