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