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