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