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