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