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