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