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