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