builtin-log.con commit format-patch: support deep threading (30984ed)
   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 **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
 463#define THREAD_SHALLOW 1
 464#define THREAD_DEEP 2
 465static int thread = 0;
 466
 467static int git_format_config(const char *var, const char *value, void *cb)
 468{
 469        if (!strcmp(var, "format.headers")) {
 470                if (!value)
 471                        die("format.headers without value");
 472                add_header(value);
 473                return 0;
 474        }
 475        if (!strcmp(var, "format.suffix"))
 476                return git_config_string(&fmt_patch_suffix, var, value);
 477        if (!strcmp(var, "format.cc")) {
 478                if (!value)
 479                        return config_error_nonbool(var);
 480                ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
 481                extra_cc[extra_cc_nr++] = xstrdup(value);
 482                return 0;
 483        }
 484        if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
 485                return 0;
 486        }
 487        if (!strcmp(var, "format.numbered")) {
 488                if (value && !strcasecmp(value, "auto")) {
 489                        auto_number = 1;
 490                        return 0;
 491                }
 492                numbered = git_config_bool(var, value);
 493                auto_number = auto_number && numbered;
 494                return 0;
 495        }
 496        if (!strcmp(var, "format.thread")) {
 497                if (value && !strcasecmp(value, "deep")) {
 498                        thread = THREAD_DEEP;
 499                        return 0;
 500                }
 501                if (value && !strcasecmp(value, "shallow")) {
 502                        thread = THREAD_SHALLOW;
 503                        return 0;
 504                }
 505                thread = git_config_bool(var, value) && THREAD_SHALLOW;
 506                return 0;
 507        }
 508
 509        return git_log_config(var, value, cb);
 510}
 511
 512
 513static const char *get_oneline_for_filename(struct commit *commit,
 514                                            int keep_subject)
 515{
 516        static char filename[PATH_MAX];
 517        char *sol;
 518        int len = 0;
 519        int suffix_len = strlen(fmt_patch_suffix) + 1;
 520
 521        sol = strstr(commit->buffer, "\n\n");
 522        if (!sol)
 523                filename[0] = '\0';
 524        else {
 525                int j, space = 0;
 526
 527                sol += 2;
 528                /* strip [PATCH] or [PATCH blabla] */
 529                if (!keep_subject && !prefixcmp(sol, "[PATCH")) {
 530                        char *eos = strchr(sol + 6, ']');
 531                        if (eos) {
 532                                while (isspace(*eos))
 533                                        eos++;
 534                                sol = eos;
 535                        }
 536                }
 537
 538                for (j = 0;
 539                     j < FORMAT_PATCH_NAME_MAX - suffix_len - 5 &&
 540                             len < sizeof(filename) - suffix_len &&
 541                             sol[j] && sol[j] != '\n';
 542                     j++) {
 543                        if (istitlechar(sol[j])) {
 544                                if (space) {
 545                                        filename[len++] = '-';
 546                                        space = 0;
 547                                }
 548                                filename[len++] = sol[j];
 549                                if (sol[j] == '.')
 550                                        while (sol[j + 1] == '.')
 551                                                j++;
 552                        } else
 553                                space = 1;
 554                }
 555                while (filename[len - 1] == '.'
 556                       || filename[len - 1] == '-')
 557                        len--;
 558                filename[len] = '\0';
 559        }
 560        return filename;
 561}
 562
 563static FILE *realstdout = NULL;
 564static const char *output_directory = NULL;
 565static int outdir_offset;
 566
 567static int reopen_stdout(const char *oneline, int nr, int total)
 568{
 569        char filename[PATH_MAX];
 570        int len = 0;
 571        int suffix_len = strlen(fmt_patch_suffix) + 1;
 572
 573        if (output_directory) {
 574                len = snprintf(filename, sizeof(filename), "%s",
 575                                output_directory);
 576                if (len >=
 577                    sizeof(filename) - FORMAT_PATCH_NAME_MAX - suffix_len)
 578                        return error("name of output directory is too long");
 579                if (filename[len - 1] != '/')
 580                        filename[len++] = '/';
 581        }
 582
 583        if (!oneline)
 584                len += sprintf(filename + len, "%d", nr);
 585        else {
 586                len += sprintf(filename + len, "%04d-", nr);
 587                len += snprintf(filename + len, sizeof(filename) - len - 1
 588                                - suffix_len, "%s", oneline);
 589                strcpy(filename + len, fmt_patch_suffix);
 590        }
 591
 592        fprintf(realstdout, "%s\n", filename + outdir_offset);
 593        if (freopen(filename, "w", stdout) == NULL)
 594                return error("Cannot open patch file %s",filename);
 595
 596        return 0;
 597}
 598
 599static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
 600{
 601        struct rev_info check_rev;
 602        struct commit *commit;
 603        struct object *o1, *o2;
 604        unsigned flags1, flags2;
 605
 606        if (rev->pending.nr != 2)
 607                die("Need exactly one range.");
 608
 609        o1 = rev->pending.objects[0].item;
 610        flags1 = o1->flags;
 611        o2 = rev->pending.objects[1].item;
 612        flags2 = o2->flags;
 613
 614        if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
 615                die("Not a range.");
 616
 617        init_patch_ids(ids);
 618
 619        /* given a range a..b get all patch ids for b..a */
 620        init_revisions(&check_rev, prefix);
 621        o1->flags ^= UNINTERESTING;
 622        o2->flags ^= UNINTERESTING;
 623        add_pending_object(&check_rev, o1, "o1");
 624        add_pending_object(&check_rev, o2, "o2");
 625        if (prepare_revision_walk(&check_rev))
 626                die("revision walk setup failed");
 627
 628        while ((commit = get_revision(&check_rev)) != NULL) {
 629                /* ignore merges */
 630                if (commit->parents && commit->parents->next)
 631                        continue;
 632
 633                add_commit_patch_id(commit, ids);
 634        }
 635
 636        /* reset for next revision walk */
 637        clear_commit_marks((struct commit *)o1,
 638                        SEEN | UNINTERESTING | SHOWN | ADDED);
 639        clear_commit_marks((struct commit *)o2,
 640                        SEEN | UNINTERESTING | SHOWN | ADDED);
 641        o1->flags = flags1;
 642        o2->flags = flags2;
 643}
 644
 645static void gen_message_id(struct rev_info *info, char *base)
 646{
 647        const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
 648        const char *email_start = strrchr(committer, '<');
 649        const char *email_end = strrchr(committer, '>');
 650        struct strbuf buf = STRBUF_INIT;
 651        if (!email_start || !email_end || email_start > email_end - 1)
 652                die("Could not extract email from committer identity.");
 653        strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
 654                    (unsigned long) time(NULL),
 655                    (int)(email_end - email_start - 1), email_start + 1);
 656        info->message_id = strbuf_detach(&buf, NULL);
 657}
 658
 659static void make_cover_letter(struct rev_info *rev, int use_stdout,
 660                              int numbered, int numbered_files,
 661                              struct commit *origin,
 662                              int nr, struct commit **list, struct commit *head)
 663{
 664        const char *committer;
 665        char *head_sha1;
 666        const char *subject_start = NULL;
 667        const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
 668        const char *msg;
 669        const char *extra_headers = rev->extra_headers;
 670        struct shortlog log;
 671        struct strbuf sb = STRBUF_INIT;
 672        int i;
 673        const char *encoding = "utf-8";
 674        struct diff_options opts;
 675        int need_8bit_cte = 0;
 676
 677        if (rev->commit_format != CMIT_FMT_EMAIL)
 678                die("Cover letter needs email format");
 679
 680        if (!use_stdout && reopen_stdout(numbered_files ?
 681                                NULL : "cover-letter", 0, rev->total))
 682                return;
 683
 684        head_sha1 = sha1_to_hex(head->object.sha1);
 685
 686        log_write_email_headers(rev, head_sha1, &subject_start, &extra_headers,
 687                                &need_8bit_cte);
 688
 689        committer = git_committer_info(0);
 690
 691        msg = body;
 692        pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
 693                     encoding);
 694        pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
 695                      encoding, need_8bit_cte);
 696        pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
 697        printf("%s\n", sb.buf);
 698
 699        strbuf_release(&sb);
 700
 701        shortlog_init(&log);
 702        log.wrap_lines = 1;
 703        log.wrap = 72;
 704        log.in1 = 2;
 705        log.in2 = 4;
 706        for (i = 0; i < nr; i++)
 707                shortlog_add_commit(&log, list[i]);
 708
 709        shortlog_output(&log);
 710
 711        /*
 712         * We can only do diffstat with a unique reference point
 713         */
 714        if (!origin)
 715                return;
 716
 717        memcpy(&opts, &rev->diffopt, sizeof(opts));
 718        opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
 719
 720        diff_setup_done(&opts);
 721
 722        diff_tree_sha1(origin->tree->object.sha1,
 723                       head->tree->object.sha1,
 724                       "", &opts);
 725        diffcore_std(&opts);
 726        diff_flush(&opts);
 727
 728        printf("\n");
 729}
 730
 731static const char *clean_message_id(const char *msg_id)
 732{
 733        char ch;
 734        const char *a, *z, *m;
 735
 736        m = msg_id;
 737        while ((ch = *m) && (isspace(ch) || (ch == '<')))
 738                m++;
 739        a = m;
 740        z = NULL;
 741        while ((ch = *m)) {
 742                if (!isspace(ch) && (ch != '>'))
 743                        z = m;
 744                m++;
 745        }
 746        if (!z)
 747                die("insane in-reply-to: %s", msg_id);
 748        if (++z == m)
 749                return a;
 750        return xmemdupz(a, z - a);
 751}
 752
 753static const char *set_outdir(const char *prefix, const char *output_directory)
 754{
 755        if (output_directory && is_absolute_path(output_directory))
 756                return output_directory;
 757
 758        if (!prefix || !*prefix) {
 759                if (output_directory)
 760                        return output_directory;
 761                /* The user did not explicitly ask for "./" */
 762                outdir_offset = 2;
 763                return "./";
 764        }
 765
 766        outdir_offset = strlen(prefix);
 767        if (!output_directory)
 768                return prefix;
 769
 770        return xstrdup(prefix_filename(prefix, outdir_offset,
 771                                       output_directory));
 772}
 773
 774int cmd_format_patch(int argc, const char **argv, const char *prefix)
 775{
 776        struct commit *commit;
 777        struct commit **list = NULL;
 778        struct rev_info rev;
 779        int nr = 0, total, i, j;
 780        int use_stdout = 0;
 781        int start_number = -1;
 782        int keep_subject = 0;
 783        int numbered_files = 0;         /* _just_ numbers */
 784        int subject_prefix = 0;
 785        int ignore_if_in_upstream = 0;
 786        int cover_letter = 0;
 787        int boundary_count = 0;
 788        int no_binary_diff = 0;
 789        struct commit *origin = NULL, *head = NULL;
 790        const char *in_reply_to = NULL;
 791        struct patch_ids ids;
 792        char *add_signoff = NULL;
 793        struct strbuf buf = STRBUF_INIT;
 794
 795        git_config(git_format_config, NULL);
 796        init_revisions(&rev, prefix);
 797        rev.commit_format = CMIT_FMT_EMAIL;
 798        rev.verbose_header = 1;
 799        rev.diff = 1;
 800        rev.combine_merges = 0;
 801        rev.ignore_merges = 1;
 802        DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
 803
 804        rev.subject_prefix = fmt_patch_subject_prefix;
 805
 806        /*
 807         * Parse the arguments before setup_revisions(), or something
 808         * like "git format-patch -o a123 HEAD^.." may fail; a123 is
 809         * possibly a valid SHA1.
 810         */
 811        for (i = 1, j = 1; i < argc; i++) {
 812                if (!strcmp(argv[i], "--stdout"))
 813                        use_stdout = 1;
 814                else if (!strcmp(argv[i], "-n") ||
 815                                !strcmp(argv[i], "--numbered"))
 816                        numbered = 1;
 817                else if (!strcmp(argv[i], "-N") ||
 818                                !strcmp(argv[i], "--no-numbered")) {
 819                        numbered = 0;
 820                        auto_number = 0;
 821                }
 822                else if (!prefixcmp(argv[i], "--start-number="))
 823                        start_number = strtol(argv[i] + 15, NULL, 10);
 824                else if (!strcmp(argv[i], "--numbered-files"))
 825                        numbered_files = 1;
 826                else if (!strcmp(argv[i], "--start-number")) {
 827                        i++;
 828                        if (i == argc)
 829                                die("Need a number for --start-number");
 830                        start_number = strtol(argv[i], NULL, 10);
 831                }
 832                else if (!prefixcmp(argv[i], "--cc=")) {
 833                        ALLOC_GROW(extra_cc, extra_cc_nr + 1, extra_cc_alloc);
 834                        extra_cc[extra_cc_nr++] = xstrdup(argv[i] + 5);
 835                }
 836                else if (!strcmp(argv[i], "-k") ||
 837                                !strcmp(argv[i], "--keep-subject")) {
 838                        keep_subject = 1;
 839                        rev.total = -1;
 840                }
 841                else if (!strcmp(argv[i], "--output-directory") ||
 842                         !strcmp(argv[i], "-o")) {
 843                        i++;
 844                        if (argc <= i)
 845                                die("Which directory?");
 846                        if (output_directory)
 847                                die("Two output directories?");
 848                        output_directory = argv[i];
 849                }
 850                else if (!strcmp(argv[i], "--signoff") ||
 851                         !strcmp(argv[i], "-s")) {
 852                        const char *committer;
 853                        const char *endpos;
 854                        committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
 855                        endpos = strchr(committer, '>');
 856                        if (!endpos)
 857                                die("bogus committer info %s", committer);
 858                        add_signoff = xmemdupz(committer, endpos - committer + 1);
 859                }
 860                else if (!strcmp(argv[i], "--attach")) {
 861                        rev.mime_boundary = git_version_string;
 862                        rev.no_inline = 1;
 863                }
 864                else if (!prefixcmp(argv[i], "--attach=")) {
 865                        rev.mime_boundary = argv[i] + 9;
 866                        rev.no_inline = 1;
 867                }
 868                else if (!strcmp(argv[i], "--inline")) {
 869                        rev.mime_boundary = git_version_string;
 870                        rev.no_inline = 0;
 871                }
 872                else if (!prefixcmp(argv[i], "--inline=")) {
 873                        rev.mime_boundary = argv[i] + 9;
 874                        rev.no_inline = 0;
 875                }
 876                else if (!strcmp(argv[i], "--ignore-if-in-upstream"))
 877                        ignore_if_in_upstream = 1;
 878                else if (!strcmp(argv[i], "--thread")
 879                        || !strcmp(argv[i], "--thread=shallow"))
 880                        thread = THREAD_SHALLOW;
 881                else if (!strcmp(argv[i], "--thread=deep"))
 882                        thread = THREAD_DEEP;
 883                else if (!strcmp(argv[i], "--no-thread"))
 884                        thread = 0;
 885                else if (!prefixcmp(argv[i], "--in-reply-to="))
 886                        in_reply_to = argv[i] + 14;
 887                else if (!strcmp(argv[i], "--in-reply-to")) {
 888                        i++;
 889                        if (i == argc)
 890                                die("Need a Message-Id for --in-reply-to");
 891                        in_reply_to = argv[i];
 892                } else if (!prefixcmp(argv[i], "--subject-prefix=")) {
 893                        subject_prefix = 1;
 894                        rev.subject_prefix = argv[i] + 17;
 895                } else if (!prefixcmp(argv[i], "--suffix="))
 896                        fmt_patch_suffix = argv[i] + 9;
 897                else if (!strcmp(argv[i], "--cover-letter"))
 898                        cover_letter = 1;
 899                else if (!strcmp(argv[i], "--no-binary"))
 900                        no_binary_diff = 1;
 901                else
 902                        argv[j++] = argv[i];
 903        }
 904        argc = j;
 905
 906        for (i = 0; i < extra_hdr_nr; i++) {
 907                strbuf_addstr(&buf, extra_hdr[i]);
 908                strbuf_addch(&buf, '\n');
 909        }
 910
 911        if (extra_to_nr)
 912                strbuf_addstr(&buf, "To: ");
 913        for (i = 0; i < extra_to_nr; i++) {
 914                if (i)
 915                        strbuf_addstr(&buf, "    ");
 916                strbuf_addstr(&buf, extra_to[i]);
 917                if (i + 1 < extra_to_nr)
 918                        strbuf_addch(&buf, ',');
 919                strbuf_addch(&buf, '\n');
 920        }
 921
 922        if (extra_cc_nr)
 923                strbuf_addstr(&buf, "Cc: ");
 924        for (i = 0; i < extra_cc_nr; i++) {
 925                if (i)
 926                        strbuf_addstr(&buf, "    ");
 927                strbuf_addstr(&buf, extra_cc[i]);
 928                if (i + 1 < extra_cc_nr)
 929                        strbuf_addch(&buf, ',');
 930                strbuf_addch(&buf, '\n');
 931        }
 932
 933        rev.extra_headers = strbuf_detach(&buf, 0);
 934
 935        if (start_number < 0)
 936                start_number = 1;
 937        if (numbered && keep_subject)
 938                die ("-n and -k are mutually exclusive.");
 939        if (keep_subject && subject_prefix)
 940                die ("--subject-prefix and -k are mutually exclusive.");
 941        if (numbered_files && use_stdout)
 942                die ("--numbered-files and --stdout are mutually exclusive.");
 943
 944        argc = setup_revisions(argc, argv, &rev, "HEAD");
 945        if (argc > 1)
 946                die ("unrecognized argument: %s", argv[1]);
 947
 948        if (!rev.diffopt.output_format
 949                || rev.diffopt.output_format == DIFF_FORMAT_PATCH)
 950                rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
 951
 952        if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
 953                DIFF_OPT_SET(&rev.diffopt, BINARY);
 954
 955        if (!use_stdout)
 956                output_directory = set_outdir(prefix, output_directory);
 957
 958        if (output_directory) {
 959                if (use_stdout)
 960                        die("standard output, or directory, which one?");
 961                if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
 962                        die("Could not create directory %s",
 963                            output_directory);
 964        }
 965
 966        if (rev.pending.nr == 1) {
 967                if (rev.max_count < 0 && !rev.show_root_diff) {
 968                        /*
 969                         * This is traditional behaviour of "git format-patch
 970                         * origin" that prepares what the origin side still
 971                         * does not have.
 972                         */
 973                        rev.pending.objects[0].item->flags |= UNINTERESTING;
 974                        add_head_to_pending(&rev);
 975                }
 976                /*
 977                 * Otherwise, it is "format-patch -22 HEAD", and/or
 978                 * "format-patch --root HEAD".  The user wants
 979                 * get_revision() to do the usual traversal.
 980                 */
 981        }
 982
 983        /*
 984         * We cannot move this anywhere earlier because we do want to
 985         * know if --root was given explicitly from the comand line.
 986         */
 987        rev.show_root_diff = 1;
 988
 989        if (cover_letter) {
 990                /* remember the range */
 991                int i;
 992                for (i = 0; i < rev.pending.nr; i++) {
 993                        struct object *o = rev.pending.objects[i].item;
 994                        if (!(o->flags & UNINTERESTING))
 995                                head = (struct commit *)o;
 996                }
 997                /* We can't generate a cover letter without any patches */
 998                if (!head)
 999                        return 0;
1000        }
1001
1002        if (ignore_if_in_upstream)
1003                get_patch_ids(&rev, &ids, prefix);
1004
1005        if (!use_stdout)
1006                realstdout = xfdopen(xdup(1), "w");
1007
1008        if (prepare_revision_walk(&rev))
1009                die("revision walk setup failed");
1010        rev.boundary = 1;
1011        while ((commit = get_revision(&rev)) != NULL) {
1012                if (commit->object.flags & BOUNDARY) {
1013                        boundary_count++;
1014                        origin = (boundary_count == 1) ? commit : NULL;
1015                        continue;
1016                }
1017
1018                /* ignore merges */
1019                if (commit->parents && commit->parents->next)
1020                        continue;
1021
1022                if (ignore_if_in_upstream &&
1023                                has_commit_patch_id(commit, &ids))
1024                        continue;
1025
1026                nr++;
1027                list = xrealloc(list, nr * sizeof(list[0]));
1028                list[nr - 1] = commit;
1029        }
1030        total = nr;
1031        if (!keep_subject && auto_number && total > 1)
1032                numbered = 1;
1033        if (numbered)
1034                rev.total = total + start_number - 1;
1035        if (in_reply_to || thread || cover_letter)
1036                rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1037        if (in_reply_to) {
1038                const char *msgid = clean_message_id(in_reply_to);
1039                string_list_append(msgid, rev.ref_message_ids);
1040        }
1041        if (cover_letter) {
1042                if (thread)
1043                        gen_message_id(&rev, "cover");
1044                make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1045                                  origin, nr, list, head);
1046                total++;
1047                start_number--;
1048        }
1049        rev.add_signoff = add_signoff;
1050        while (0 <= --nr) {
1051                int shown;
1052                commit = list[nr];
1053                rev.nr = total - nr + (start_number - 1);
1054                /* Make the second and subsequent mails replies to the first */
1055                if (thread) {
1056                        /* Have we already had a message ID? */
1057                        if (rev.message_id) {
1058                                /*
1059                                 * For deep threading: make every mail
1060                                 * a reply to the previous one, no
1061                                 * matter what other options are set.
1062                                 *
1063                                 * For shallow threading:
1064                                 *
1065                                 * Without --cover-letter and
1066                                 * --in-reply-to, make every mail a
1067                                 * reply to the one before.
1068                                 *
1069                                 * With --in-reply-to but no
1070                                 * --cover-letter, make every mail a
1071                                 * reply to the <reply-to>.
1072                                 *
1073                                 * With --cover-letter, make every
1074                                 * mail but the cover letter a reply
1075                                 * to the cover letter.  The cover
1076                                 * letter is a reply to the
1077                                 * --in-reply-to, if specified.
1078                                 */
1079                                if (thread == THREAD_SHALLOW
1080                                    && rev.ref_message_ids->nr > 0
1081                                    && (!cover_letter || rev.nr > 1))
1082                                        free(rev.message_id);
1083                                else
1084                                        string_list_append(rev.message_id,
1085                                                           rev.ref_message_ids);
1086                        }
1087                        gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1088                }
1089                if (!use_stdout && reopen_stdout(numbered_files ? NULL :
1090                                get_oneline_for_filename(commit, keep_subject),
1091                                rev.nr, rev.total))
1092                        die("Failed to create output files");
1093                shown = log_tree_commit(&rev, commit);
1094                free(commit->buffer);
1095                commit->buffer = NULL;
1096
1097                /* We put one extra blank line between formatted
1098                 * patches and this flag is used by log-tree code
1099                 * to see if it needs to emit a LF before showing
1100                 * the log; when using one file per patch, we do
1101                 * not want the extra blank line.
1102                 */
1103                if (!use_stdout)
1104                        rev.shown_one = 0;
1105                if (shown) {
1106                        if (rev.mime_boundary)
1107                                printf("\n--%s%s--\n\n\n",
1108                                       mime_boundary_leader,
1109                                       rev.mime_boundary);
1110                        else
1111                                printf("-- \n%s\n\n", git_version_string);
1112                }
1113                if (!use_stdout)
1114                        fclose(stdout);
1115        }
1116        free(list);
1117        if (ignore_if_in_upstream)
1118                free_patch_ids(&ids);
1119        return 0;
1120}
1121
1122static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1123{
1124        unsigned char sha1[20];
1125        if (get_sha1(arg, sha1) == 0) {
1126                struct commit *commit = lookup_commit_reference(sha1);
1127                if (commit) {
1128                        commit->object.flags |= flags;
1129                        add_pending_object(revs, &commit->object, arg);
1130                        return 0;
1131                }
1132        }
1133        return -1;
1134}
1135
1136static const char cherry_usage[] =
1137"git cherry [-v] [<upstream> [<head> [<limit>]]]";
1138int cmd_cherry(int argc, const char **argv, const char *prefix)
1139{
1140        struct rev_info revs;
1141        struct patch_ids ids;
1142        struct commit *commit;
1143        struct commit_list *list = NULL;
1144        struct branch *current_branch;
1145        const char *upstream;
1146        const char *head = "HEAD";
1147        const char *limit = NULL;
1148        int verbose = 0;
1149
1150        if (argc > 1 && !strcmp(argv[1], "-v")) {
1151                verbose = 1;
1152                argc--;
1153                argv++;
1154        }
1155
1156        switch (argc) {
1157        case 4:
1158                limit = argv[3];
1159                /* FALLTHROUGH */
1160        case 3:
1161                head = argv[2];
1162                /* FALLTHROUGH */
1163        case 2:
1164                upstream = argv[1];
1165                break;
1166        default:
1167                current_branch = branch_get(NULL);
1168                if (!current_branch || !current_branch->merge
1169                                        || !current_branch->merge[0]
1170                                        || !current_branch->merge[0]->dst) {
1171                        fprintf(stderr, "Could not find a tracked"
1172                                        " remote branch, please"
1173                                        " specify <upstream> manually.\n");
1174                        usage(cherry_usage);
1175                }
1176
1177                upstream = current_branch->merge[0]->dst;
1178        }
1179
1180        init_revisions(&revs, prefix);
1181        revs.diff = 1;
1182        revs.combine_merges = 0;
1183        revs.ignore_merges = 1;
1184        DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1185
1186        if (add_pending_commit(head, &revs, 0))
1187                die("Unknown commit %s", head);
1188        if (add_pending_commit(upstream, &revs, UNINTERESTING))
1189                die("Unknown commit %s", upstream);
1190
1191        /* Don't say anything if head and upstream are the same. */
1192        if (revs.pending.nr == 2) {
1193                struct object_array_entry *o = revs.pending.objects;
1194                if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1195                        return 0;
1196        }
1197
1198        get_patch_ids(&revs, &ids, prefix);
1199
1200        if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1201                die("Unknown commit %s", limit);
1202
1203        /* reverse the list of commits */
1204        if (prepare_revision_walk(&revs))
1205                die("revision walk setup failed");
1206        while ((commit = get_revision(&revs)) != NULL) {
1207                /* ignore merges */
1208                if (commit->parents && commit->parents->next)
1209                        continue;
1210
1211                commit_list_insert(commit, &list);
1212        }
1213
1214        while (list) {
1215                char sign = '+';
1216
1217                commit = list->item;
1218                if (has_commit_patch_id(commit, &ids))
1219                        sign = '-';
1220
1221                if (verbose) {
1222                        struct strbuf buf = STRBUF_INIT;
1223                        pretty_print_commit(CMIT_FMT_ONELINE, commit,
1224                                            &buf, 0, NULL, NULL, 0, 0);
1225                        printf("%c %s %s\n", sign,
1226                               sha1_to_hex(commit->object.sha1), buf.buf);
1227                        strbuf_release(&buf);
1228                }
1229                else {
1230                        printf("%c %s\n", sign,
1231                               sha1_to_hex(commit->object.sha1));
1232                }
1233
1234                list = list->next;
1235        }
1236
1237        free_patch_ids(&ids);
1238        return 0;
1239}