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