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