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