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