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