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