builtin-log.con commit Fix parent rewriting in --early-output (7dc0fe3)
   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 "commit.h"
   9#include "diff.h"
  10#include "revision.h"
  11#include "log-tree.h"
  12#include "builtin.h"
  13#include "tag.h"
  14#include "reflog-walk.h"
  15#include "patch-ids.h"
  16#include "refs.h"
  17
  18static int default_show_root = 1;
  19static const char *fmt_patch_subject_prefix = "PATCH";
  20
  21/* this is in builtin-diff.c */
  22void add_head(struct rev_info *revs);
  23
  24static void add_name_decoration(const char *prefix, const char *name, struct object *obj)
  25{
  26        int plen = strlen(prefix);
  27        int nlen = strlen(name);
  28        struct name_decoration *res = xmalloc(sizeof(struct name_decoration) + plen + nlen);
  29        memcpy(res->name, prefix, plen);
  30        memcpy(res->name + plen, name, nlen + 1);
  31        res->next = add_decoration(&name_decoration, obj, res);
  32}
  33
  34static int add_ref_decoration(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
  35{
  36        struct object *obj = parse_object(sha1);
  37        if (!obj)
  38                return 0;
  39        add_name_decoration("", refname, obj);
  40        while (obj->type == OBJ_TAG) {
  41                obj = ((struct tag *)obj)->tagged;
  42                if (!obj)
  43                        break;
  44                add_name_decoration("tag: ", refname, obj);
  45        }
  46        return 0;
  47}
  48
  49static void cmd_log_init(int argc, const char **argv, const char *prefix,
  50                      struct rev_info *rev)
  51{
  52        int i;
  53        int decorate = 0;
  54
  55        rev->abbrev = DEFAULT_ABBREV;
  56        rev->commit_format = CMIT_FMT_DEFAULT;
  57        rev->verbose_header = 1;
  58        rev->diffopt.recursive = 1;
  59        rev->show_root_diff = default_show_root;
  60        rev->subject_prefix = fmt_patch_subject_prefix;
  61        argc = setup_revisions(argc, argv, rev, "HEAD");
  62        if (rev->diffopt.pickaxe || rev->diffopt.filter)
  63                rev->always_show_header = 0;
  64        if (rev->diffopt.follow_renames) {
  65                rev->always_show_header = 0;
  66                if (rev->diffopt.nr_paths != 1)
  67                        usage("git logs can only follow renames on one pathname at a time");
  68        }
  69        for (i = 1; i < argc; i++) {
  70                const char *arg = argv[i];
  71                if (!strcmp(arg, "--decorate")) {
  72                        if (!decorate)
  73                                for_each_ref(add_ref_decoration, NULL);
  74                        decorate = 1;
  75                } else
  76                        die("unrecognized argument: %s", arg);
  77        }
  78}
  79
  80/*
  81 * This gives a rough estimate for how many commits we
  82 * will print out in the list.
  83 */
  84static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
  85{
  86        int n = 0;
  87
  88        while (list) {
  89                struct commit *commit = list->item;
  90                unsigned int flags = commit->object.flags;
  91                list = list->next;
  92                if (!(flags & (TREESAME | UNINTERESTING)))
  93                        n++;
  94        }
  95        return n;
  96}
  97
  98static void show_early_header(struct rev_info *rev, const char *stage, int nr)
  99{
 100        if (rev->shown_one) {
 101                rev->shown_one = 0;
 102                if (rev->commit_format != CMIT_FMT_ONELINE)
 103                        putchar(rev->diffopt.line_termination);
 104        }
 105        printf("Final output: %d %s\n", nr, stage);
 106}
 107
 108struct itimerval early_output_timer;
 109
 110static void log_show_early(struct rev_info *revs, struct commit_list *list)
 111{
 112        int i = revs->early_output;
 113        int show_header = 1;
 114
 115        sort_in_topological_order(&list, revs->lifo);
 116        while (list && i) {
 117                struct commit *commit = list->item;
 118                switch (simplify_commit(revs, commit)) {
 119                case commit_show:
 120                        if (show_header) {
 121                                int n = estimate_commit_count(revs, list);
 122                                show_early_header(revs, "incomplete", n);
 123                                show_header = 0;
 124                        }
 125                        log_tree_commit(revs, commit);
 126                        i--;
 127                        break;
 128                case commit_ignore:
 129                        break;
 130                case commit_error:
 131                        return;
 132                }
 133                list = list->next;
 134        }
 135
 136        /* Did we already get enough commits for the early output? */
 137        if (!i)
 138                return;
 139
 140        /*
 141         * ..if no, then repeat it twice a second until we
 142         * do.
 143         *
 144         * NOTE! We don't use "it_interval", because if the
 145         * reader isn't listening, we want our output to be
 146         * throttled by the writing, and not have the timer
 147         * trigger every second even if we're blocked on a
 148         * reader!
 149         */
 150        early_output_timer.it_value.tv_sec = 0;
 151        early_output_timer.it_value.tv_usec = 500000;
 152        setitimer(ITIMER_REAL, &early_output_timer, NULL);
 153}
 154
 155static void early_output(int signal)
 156{
 157        show_early_output = log_show_early;
 158}
 159
 160static void setup_early_output(struct rev_info *rev)
 161{
 162        struct sigaction sa;
 163
 164        /*
 165         * Set up the signal handler, minimally intrusively:
 166         * we only set a single volatile integer word (not
 167         * using sigatomic_t - trying to avoid unnecessary
 168         * system dependencies and headers), and using
 169         * SA_RESTART.
 170         */
 171        memset(&sa, 0, sizeof(sa));
 172        sa.sa_handler = early_output;
 173        sigemptyset(&sa.sa_mask);
 174        sa.sa_flags = SA_RESTART;
 175        sigaction(SIGALRM, &sa, NULL);
 176
 177        /*
 178         * If we can get the whole output in less than a
 179         * tenth of a second, don't even bother doing the
 180         * early-output thing..
 181         *
 182         * This is a one-time-only trigger.
 183         */
 184        early_output_timer.it_value.tv_sec = 0;
 185        early_output_timer.it_value.tv_usec = 100000;
 186        setitimer(ITIMER_REAL, &early_output_timer, NULL);
 187}
 188
 189static void finish_early_output(struct rev_info *rev)
 190{
 191        int n = estimate_commit_count(rev, rev->commits);
 192        signal(SIGALRM, SIG_IGN);
 193        show_early_header(rev, "done", n);
 194}
 195
 196static int cmd_log_walk(struct rev_info *rev)
 197{
 198        struct commit *commit;
 199
 200        if (rev->early_output)
 201                setup_early_output(rev);
 202
 203        prepare_revision_walk(rev);
 204
 205        if (rev->early_output)
 206                finish_early_output(rev);
 207
 208        while ((commit = get_revision(rev)) != NULL) {
 209                log_tree_commit(rev, commit);
 210                if (!rev->reflog_info) {
 211                        /* we allow cycles in reflog ancestry */
 212                        free(commit->buffer);
 213                        commit->buffer = NULL;
 214                }
 215                free_commit_list(commit->parents);
 216                commit->parents = NULL;
 217        }
 218        return 0;
 219}
 220
 221static int git_log_config(const char *var, const char *value)
 222{
 223        if (!strcmp(var, "format.subjectprefix")) {
 224                if (!value)
 225                        die("format.subjectprefix without value");
 226                fmt_patch_subject_prefix = xstrdup(value);
 227                return 0;
 228        }
 229        if (!strcmp(var, "log.showroot")) {
 230                default_show_root = git_config_bool(var, value);
 231                return 0;
 232        }
 233        return git_diff_ui_config(var, value);
 234}
 235
 236int cmd_whatchanged(int argc, const char **argv, const char *prefix)
 237{
 238        struct rev_info rev;
 239
 240        git_config(git_log_config);
 241        init_revisions(&rev, prefix);
 242        rev.diff = 1;
 243        rev.simplify_history = 0;
 244        cmd_log_init(argc, argv, prefix, &rev);
 245        if (!rev.diffopt.output_format)
 246                rev.diffopt.output_format = DIFF_FORMAT_RAW;
 247        return cmd_log_walk(&rev);
 248}
 249
 250static int show_object(const unsigned char *sha1, int suppress_header)
 251{
 252        unsigned long size;
 253        enum object_type type;
 254        char *buf = read_sha1_file(sha1, &type, &size);
 255        int offset = 0;
 256
 257        if (!buf)
 258                return error("Could not read object %s", sha1_to_hex(sha1));
 259
 260        if (suppress_header)
 261                while (offset < size && buf[offset++] != '\n') {
 262                        int new_offset = offset;
 263                        while (new_offset < size && buf[new_offset++] != '\n')
 264                                ; /* do nothing */
 265                        offset = new_offset;
 266                }
 267
 268        if (offset < size)
 269                fwrite(buf + offset, size - offset, 1, stdout);
 270        free(buf);
 271        return 0;
 272}
 273
 274static int show_tree_object(const unsigned char *sha1,
 275                const char *base, int baselen,
 276                const char *pathname, unsigned mode, int stage)
 277{
 278        printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
 279        return 0;
 280}
 281
 282int cmd_show(int argc, const char **argv, const char *prefix)
 283{
 284        struct rev_info rev;
 285        struct object_array_entry *objects;
 286        int i, count, ret = 0;
 287
 288        git_config(git_log_config);
 289        init_revisions(&rev, prefix);
 290        rev.diff = 1;
 291        rev.combine_merges = 1;
 292        rev.dense_combined_merges = 1;
 293        rev.always_show_header = 1;
 294        rev.ignore_merges = 0;
 295        rev.no_walk = 1;
 296        cmd_log_init(argc, argv, prefix, &rev);
 297
 298        count = rev.pending.nr;
 299        objects = rev.pending.objects;
 300        for (i = 0; i < count && !ret; i++) {
 301                struct object *o = objects[i].item;
 302                const char *name = objects[i].name;
 303                switch (o->type) {
 304                case OBJ_BLOB:
 305                        ret = show_object(o->sha1, 0);
 306                        break;
 307                case OBJ_TAG: {
 308                        struct tag *t = (struct tag *)o;
 309
 310                        printf("%stag %s%s\n\n",
 311                                        diff_get_color(rev.diffopt.color_diff,
 312                                                DIFF_COMMIT),
 313                                        t->tag,
 314                                        diff_get_color(rev.diffopt.color_diff,
 315                                                DIFF_RESET));
 316                        ret = show_object(o->sha1, 1);
 317                        objects[i].item = (struct object *)t->tagged;
 318                        i--;
 319                        break;
 320                }
 321                case OBJ_TREE:
 322                        printf("%stree %s%s\n\n",
 323                                        diff_get_color(rev.diffopt.color_diff,
 324                                                DIFF_COMMIT),
 325                                        name,
 326                                        diff_get_color(rev.diffopt.color_diff,
 327                                                DIFF_RESET));
 328                        read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
 329                                        show_tree_object);
 330                        break;
 331                case OBJ_COMMIT:
 332                        rev.pending.nr = rev.pending.alloc = 0;
 333                        rev.pending.objects = NULL;
 334                        add_object_array(o, name, &rev.pending);
 335                        ret = cmd_log_walk(&rev);
 336                        break;
 337                default:
 338                        ret = error("Unknown type: %d", o->type);
 339                }
 340        }
 341        free(objects);
 342        return ret;
 343}
 344
 345/*
 346 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
 347 */
 348int cmd_log_reflog(int argc, const char **argv, const char *prefix)
 349{
 350        struct rev_info rev;
 351
 352        git_config(git_log_config);
 353        init_revisions(&rev, prefix);
 354        init_reflog_walk(&rev.reflog_info);
 355        rev.abbrev_commit = 1;
 356        rev.verbose_header = 1;
 357        cmd_log_init(argc, argv, prefix, &rev);
 358
 359        /*
 360         * This means that we override whatever commit format the user gave
 361         * on the cmd line.  Sad, but cmd_log_init() currently doesn't
 362         * allow us to set a different default.
 363         */
 364        rev.commit_format = CMIT_FMT_ONELINE;
 365        rev.always_show_header = 1;
 366
 367        /*
 368         * We get called through "git reflog", so unlike the other log
 369         * routines, we need to set up our pager manually..
 370         */
 371        setup_pager();
 372
 373        return cmd_log_walk(&rev);
 374}
 375
 376int cmd_log(int argc, const char **argv, const char *prefix)
 377{
 378        struct rev_info rev;
 379
 380        git_config(git_log_config);
 381        init_revisions(&rev, prefix);
 382        rev.always_show_header = 1;
 383        cmd_log_init(argc, argv, prefix, &rev);
 384        return cmd_log_walk(&rev);
 385}
 386
 387/* format-patch */
 388#define FORMAT_PATCH_NAME_MAX 64
 389
 390static int istitlechar(char c)
 391{
 392        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
 393                (c >= '0' && c <= '9') || c == '.' || c == '_';
 394}
 395
 396static char *extra_headers = NULL;
 397static int extra_headers_size = 0;
 398static const char *fmt_patch_suffix = ".patch";
 399
 400static int git_format_config(const char *var, const char *value)
 401{
 402        if (!strcmp(var, "format.headers")) {
 403                int len;
 404
 405                if (!value)
 406                        die("format.headers without value");
 407                len = strlen(value);
 408                extra_headers_size += len + 1;
 409                extra_headers = xrealloc(extra_headers, extra_headers_size);
 410                extra_headers[extra_headers_size - len - 1] = 0;
 411                strcat(extra_headers, value);
 412                return 0;
 413        }
 414        if (!strcmp(var, "format.suffix")) {
 415                if (!value)
 416                        die("format.suffix without value");
 417                fmt_patch_suffix = xstrdup(value);
 418                return 0;
 419        }
 420        if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
 421                return 0;
 422        }
 423
 424        return git_log_config(var, value);
 425}
 426
 427
 428static FILE *realstdout = NULL;
 429static const char *output_directory = NULL;
 430
 431static int reopen_stdout(struct commit *commit, int nr, int keep_subject,
 432                         int numbered_files)
 433{
 434        char filename[PATH_MAX];
 435        char *sol;
 436        int len = 0;
 437        int suffix_len = strlen(fmt_patch_suffix) + 1;
 438
 439        if (output_directory) {
 440                if (strlen(output_directory) >=
 441                    sizeof(filename) - FORMAT_PATCH_NAME_MAX - suffix_len)
 442                        return error("name of output directory is too long");
 443                strlcpy(filename, output_directory, sizeof(filename) - suffix_len);
 444                len = strlen(filename);
 445                if (filename[len - 1] != '/')
 446                        filename[len++] = '/';
 447        }
 448
 449        if (numbered_files) {
 450                sprintf(filename + len, "%d", nr);
 451                len = strlen(filename);
 452
 453        } else {
 454                sprintf(filename + len, "%04d", nr);
 455                len = strlen(filename);
 456
 457                sol = strstr(commit->buffer, "\n\n");
 458                if (sol) {
 459                        int j, space = 1;
 460
 461                        sol += 2;
 462                        /* strip [PATCH] or [PATCH blabla] */
 463                        if (!keep_subject && !prefixcmp(sol, "[PATCH")) {
 464                                char *eos = strchr(sol + 6, ']');
 465                                if (eos) {
 466                                        while (isspace(*eos))
 467                                                eos++;
 468                                        sol = eos;
 469                                }
 470                        }
 471
 472                        for (j = 0;
 473                             j < FORMAT_PATCH_NAME_MAX - suffix_len - 5 &&
 474                                     len < sizeof(filename) - suffix_len &&
 475                                     sol[j] && sol[j] != '\n';
 476                             j++) {
 477                                if (istitlechar(sol[j])) {
 478                                        if (space) {
 479                                                filename[len++] = '-';
 480                                                space = 0;
 481                                        }
 482                                        filename[len++] = sol[j];
 483                                        if (sol[j] == '.')
 484                                                while (sol[j + 1] == '.')
 485                                                        j++;
 486                                } else
 487                                        space = 1;
 488                        }
 489                        while (filename[len - 1] == '.'
 490                               || filename[len - 1] == '-')
 491                                len--;
 492                        filename[len] = 0;
 493                }
 494                if (len + suffix_len >= sizeof(filename))
 495                        return error("Patch pathname too long");
 496                strcpy(filename + len, fmt_patch_suffix);
 497        }
 498
 499        fprintf(realstdout, "%s\n", filename);
 500        if (freopen(filename, "w", stdout) == NULL)
 501                return error("Cannot open patch file %s",filename);
 502
 503        return 0;
 504}
 505
 506static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
 507{
 508        struct rev_info check_rev;
 509        struct commit *commit;
 510        struct object *o1, *o2;
 511        unsigned flags1, flags2;
 512
 513        if (rev->pending.nr != 2)
 514                die("Need exactly one range.");
 515
 516        o1 = rev->pending.objects[0].item;
 517        flags1 = o1->flags;
 518        o2 = rev->pending.objects[1].item;
 519        flags2 = o2->flags;
 520
 521        if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
 522                die("Not a range.");
 523
 524        init_patch_ids(ids);
 525
 526        /* given a range a..b get all patch ids for b..a */
 527        init_revisions(&check_rev, prefix);
 528        o1->flags ^= UNINTERESTING;
 529        o2->flags ^= UNINTERESTING;
 530        add_pending_object(&check_rev, o1, "o1");
 531        add_pending_object(&check_rev, o2, "o2");
 532        prepare_revision_walk(&check_rev);
 533
 534        while ((commit = get_revision(&check_rev)) != NULL) {
 535                /* ignore merges */
 536                if (commit->parents && commit->parents->next)
 537                        continue;
 538
 539                add_commit_patch_id(commit, ids);
 540        }
 541
 542        /* reset for next revision walk */
 543        clear_commit_marks((struct commit *)o1,
 544                        SEEN | UNINTERESTING | SHOWN | ADDED);
 545        clear_commit_marks((struct commit *)o2,
 546                        SEEN | UNINTERESTING | SHOWN | ADDED);
 547        o1->flags = flags1;
 548        o2->flags = flags2;
 549}
 550
 551static void gen_message_id(char *dest, unsigned int length, char *base)
 552{
 553        const char *committer = git_committer_info(-1);
 554        const char *email_start = strrchr(committer, '<');
 555        const char *email_end = strrchr(committer, '>');
 556        if(!email_start || !email_end || email_start > email_end - 1)
 557                die("Could not extract email from committer identity.");
 558        snprintf(dest, length, "%s.%lu.git.%.*s", base,
 559                 (unsigned long) time(NULL),
 560                 (int)(email_end - email_start - 1), email_start + 1);
 561}
 562
 563static const char *clean_message_id(const char *msg_id)
 564{
 565        char ch;
 566        const char *a, *z, *m;
 567
 568        m = msg_id;
 569        while ((ch = *m) && (isspace(ch) || (ch == '<')))
 570                m++;
 571        a = m;
 572        z = NULL;
 573        while ((ch = *m)) {
 574                if (!isspace(ch) && (ch != '>'))
 575                        z = m;
 576                m++;
 577        }
 578        if (!z)
 579                die("insane in-reply-to: %s", msg_id);
 580        if (++z == m)
 581                return a;
 582        return xmemdupz(a, z - a);
 583}
 584
 585int cmd_format_patch(int argc, const char **argv, const char *prefix)
 586{
 587        struct commit *commit;
 588        struct commit **list = NULL;
 589        struct rev_info rev;
 590        int nr = 0, total, i, j;
 591        int use_stdout = 0;
 592        int numbered = 0;
 593        int start_number = -1;
 594        int keep_subject = 0;
 595        int numbered_files = 0;         /* _just_ numbers */
 596        int subject_prefix = 0;
 597        int ignore_if_in_upstream = 0;
 598        int thread = 0;
 599        const char *in_reply_to = NULL;
 600        struct patch_ids ids;
 601        char *add_signoff = NULL;
 602        char message_id[1024];
 603        char ref_message_id[1024];
 604
 605        git_config(git_format_config);
 606        init_revisions(&rev, prefix);
 607        rev.commit_format = CMIT_FMT_EMAIL;
 608        rev.verbose_header = 1;
 609        rev.diff = 1;
 610        rev.combine_merges = 0;
 611        rev.ignore_merges = 1;
 612        rev.diffopt.msg_sep = "";
 613        rev.diffopt.recursive = 1;
 614
 615        rev.subject_prefix = fmt_patch_subject_prefix;
 616        rev.extra_headers = extra_headers;
 617
 618        /*
 619         * Parse the arguments before setup_revisions(), or something
 620         * like "git format-patch -o a123 HEAD^.." may fail; a123 is
 621         * possibly a valid SHA1.
 622         */
 623        for (i = 1, j = 1; i < argc; i++) {
 624                if (!strcmp(argv[i], "--stdout"))
 625                        use_stdout = 1;
 626                else if (!strcmp(argv[i], "-n") ||
 627                                !strcmp(argv[i], "--numbered"))
 628                        numbered = 1;
 629                else if (!prefixcmp(argv[i], "--start-number="))
 630                        start_number = strtol(argv[i] + 15, NULL, 10);
 631                else if (!strcmp(argv[i], "--numbered-files"))
 632                        numbered_files = 1;
 633                else if (!strcmp(argv[i], "--start-number")) {
 634                        i++;
 635                        if (i == argc)
 636                                die("Need a number for --start-number");
 637                        start_number = strtol(argv[i], NULL, 10);
 638                }
 639                else if (!strcmp(argv[i], "-k") ||
 640                                !strcmp(argv[i], "--keep-subject")) {
 641                        keep_subject = 1;
 642                        rev.total = -1;
 643                }
 644                else if (!strcmp(argv[i], "--output-directory") ||
 645                         !strcmp(argv[i], "-o")) {
 646                        i++;
 647                        if (argc <= i)
 648                                die("Which directory?");
 649                        if (output_directory)
 650                                die("Two output directories?");
 651                        output_directory = argv[i];
 652                }
 653                else if (!strcmp(argv[i], "--signoff") ||
 654                         !strcmp(argv[i], "-s")) {
 655                        const char *committer;
 656                        const char *endpos;
 657                        committer = git_committer_info(1);
 658                        endpos = strchr(committer, '>');
 659                        if (!endpos)
 660                                die("bogos committer info %s\n", committer);
 661                        add_signoff = xmemdupz(committer, endpos - committer + 1);
 662                }
 663                else if (!strcmp(argv[i], "--attach")) {
 664                        rev.mime_boundary = git_version_string;
 665                        rev.no_inline = 1;
 666                }
 667                else if (!prefixcmp(argv[i], "--attach=")) {
 668                        rev.mime_boundary = argv[i] + 9;
 669                        rev.no_inline = 1;
 670                }
 671                else if (!strcmp(argv[i], "--inline")) {
 672                        rev.mime_boundary = git_version_string;
 673                        rev.no_inline = 0;
 674                }
 675                else if (!prefixcmp(argv[i], "--inline=")) {
 676                        rev.mime_boundary = argv[i] + 9;
 677                        rev.no_inline = 0;
 678                }
 679                else if (!strcmp(argv[i], "--ignore-if-in-upstream"))
 680                        ignore_if_in_upstream = 1;
 681                else if (!strcmp(argv[i], "--thread"))
 682                        thread = 1;
 683                else if (!prefixcmp(argv[i], "--in-reply-to="))
 684                        in_reply_to = argv[i] + 14;
 685                else if (!strcmp(argv[i], "--in-reply-to")) {
 686                        i++;
 687                        if (i == argc)
 688                                die("Need a Message-Id for --in-reply-to");
 689                        in_reply_to = argv[i];
 690                } else if (!prefixcmp(argv[i], "--subject-prefix=")) {
 691                        subject_prefix = 1;
 692                        rev.subject_prefix = argv[i] + 17;
 693                } else if (!prefixcmp(argv[i], "--suffix="))
 694                        fmt_patch_suffix = argv[i] + 9;
 695                else
 696                        argv[j++] = argv[i];
 697        }
 698        argc = j;
 699
 700        if (start_number < 0)
 701                start_number = 1;
 702        if (numbered && keep_subject)
 703                die ("-n and -k are mutually exclusive.");
 704        if (keep_subject && subject_prefix)
 705                die ("--subject-prefix and -k are mutually exclusive.");
 706        if (numbered_files && use_stdout)
 707                die ("--numbered-files and --stdout are mutually exclusive.");
 708
 709        argc = setup_revisions(argc, argv, &rev, "HEAD");
 710        if (argc > 1)
 711                die ("unrecognized argument: %s", argv[1]);
 712
 713        if (!rev.diffopt.output_format)
 714                rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
 715
 716        if (!rev.diffopt.text)
 717                rev.diffopt.binary = 1;
 718
 719        if (!output_directory && !use_stdout)
 720                output_directory = prefix;
 721
 722        if (output_directory) {
 723                if (use_stdout)
 724                        die("standard output, or directory, which one?");
 725                if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
 726                        die("Could not create directory %s",
 727                            output_directory);
 728        }
 729
 730        if (rev.pending.nr == 1) {
 731                if (rev.max_count < 0 && !rev.show_root_diff) {
 732                        /*
 733                         * This is traditional behaviour of "git format-patch
 734                         * origin" that prepares what the origin side still
 735                         * does not have.
 736                         */
 737                        rev.pending.objects[0].item->flags |= UNINTERESTING;
 738                        add_head(&rev);
 739                }
 740                /*
 741                 * Otherwise, it is "format-patch -22 HEAD", and/or
 742                 * "format-patch --root HEAD".  The user wants
 743                 * get_revision() to do the usual traversal.
 744                 */
 745        }
 746
 747        if (ignore_if_in_upstream)
 748                get_patch_ids(&rev, &ids, prefix);
 749
 750        if (!use_stdout)
 751                realstdout = xfdopen(xdup(1), "w");
 752
 753        prepare_revision_walk(&rev);
 754        while ((commit = get_revision(&rev)) != NULL) {
 755                /* ignore merges */
 756                if (commit->parents && commit->parents->next)
 757                        continue;
 758
 759                if (ignore_if_in_upstream &&
 760                                has_commit_patch_id(commit, &ids))
 761                        continue;
 762
 763                nr++;
 764                list = xrealloc(list, nr * sizeof(list[0]));
 765                list[nr - 1] = commit;
 766        }
 767        total = nr;
 768        if (numbered)
 769                rev.total = total + start_number - 1;
 770        rev.add_signoff = add_signoff;
 771        if (in_reply_to)
 772                rev.ref_message_id = clean_message_id(in_reply_to);
 773        while (0 <= --nr) {
 774                int shown;
 775                commit = list[nr];
 776                rev.nr = total - nr + (start_number - 1);
 777                /* Make the second and subsequent mails replies to the first */
 778                if (thread) {
 779                        if (nr == (total - 2)) {
 780                                strncpy(ref_message_id, message_id,
 781                                        sizeof(ref_message_id));
 782                                ref_message_id[sizeof(ref_message_id)-1]='\0';
 783                                rev.ref_message_id = ref_message_id;
 784                        }
 785                        gen_message_id(message_id, sizeof(message_id),
 786                                       sha1_to_hex(commit->object.sha1));
 787                        rev.message_id = message_id;
 788                }
 789                if (!use_stdout)
 790                        if (reopen_stdout(commit, rev.nr, keep_subject,
 791                                          numbered_files))
 792                                die("Failed to create output files");
 793                shown = log_tree_commit(&rev, commit);
 794                free(commit->buffer);
 795                commit->buffer = NULL;
 796
 797                /* We put one extra blank line between formatted
 798                 * patches and this flag is used by log-tree code
 799                 * to see if it needs to emit a LF before showing
 800                 * the log; when using one file per patch, we do
 801                 * not want the extra blank line.
 802                 */
 803                if (!use_stdout)
 804                        rev.shown_one = 0;
 805                if (shown) {
 806                        if (rev.mime_boundary)
 807                                printf("\n--%s%s--\n\n\n",
 808                                       mime_boundary_leader,
 809                                       rev.mime_boundary);
 810                        else
 811                                printf("-- \n%s\n\n", git_version_string);
 812                }
 813                if (!use_stdout)
 814                        fclose(stdout);
 815        }
 816        free(list);
 817        if (ignore_if_in_upstream)
 818                free_patch_ids(&ids);
 819        return 0;
 820}
 821
 822static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
 823{
 824        unsigned char sha1[20];
 825        if (get_sha1(arg, sha1) == 0) {
 826                struct commit *commit = lookup_commit_reference(sha1);
 827                if (commit) {
 828                        commit->object.flags |= flags;
 829                        add_pending_object(revs, &commit->object, arg);
 830                        return 0;
 831                }
 832        }
 833        return -1;
 834}
 835
 836static const char cherry_usage[] =
 837"git-cherry [-v] <upstream> [<head>] [<limit>]";
 838int cmd_cherry(int argc, const char **argv, const char *prefix)
 839{
 840        struct rev_info revs;
 841        struct patch_ids ids;
 842        struct commit *commit;
 843        struct commit_list *list = NULL;
 844        const char *upstream;
 845        const char *head = "HEAD";
 846        const char *limit = NULL;
 847        int verbose = 0;
 848
 849        if (argc > 1 && !strcmp(argv[1], "-v")) {
 850                verbose = 1;
 851                argc--;
 852                argv++;
 853        }
 854
 855        switch (argc) {
 856        case 4:
 857                limit = argv[3];
 858                /* FALLTHROUGH */
 859        case 3:
 860                head = argv[2];
 861                /* FALLTHROUGH */
 862        case 2:
 863                upstream = argv[1];
 864                break;
 865        default:
 866                usage(cherry_usage);
 867        }
 868
 869        init_revisions(&revs, prefix);
 870        revs.diff = 1;
 871        revs.combine_merges = 0;
 872        revs.ignore_merges = 1;
 873        revs.diffopt.recursive = 1;
 874
 875        if (add_pending_commit(head, &revs, 0))
 876                die("Unknown commit %s", head);
 877        if (add_pending_commit(upstream, &revs, UNINTERESTING))
 878                die("Unknown commit %s", upstream);
 879
 880        /* Don't say anything if head and upstream are the same. */
 881        if (revs.pending.nr == 2) {
 882                struct object_array_entry *o = revs.pending.objects;
 883                if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
 884                        return 0;
 885        }
 886
 887        get_patch_ids(&revs, &ids, prefix);
 888
 889        if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
 890                die("Unknown commit %s", limit);
 891
 892        /* reverse the list of commits */
 893        prepare_revision_walk(&revs);
 894        while ((commit = get_revision(&revs)) != NULL) {
 895                /* ignore merges */
 896                if (commit->parents && commit->parents->next)
 897                        continue;
 898
 899                commit_list_insert(commit, &list);
 900        }
 901
 902        while (list) {
 903                char sign = '+';
 904
 905                commit = list->item;
 906                if (has_commit_patch_id(commit, &ids))
 907                        sign = '-';
 908
 909                if (verbose) {
 910                        struct strbuf buf;
 911                        strbuf_init(&buf, 0);
 912                        pretty_print_commit(CMIT_FMT_ONELINE, commit,
 913                                            &buf, 0, NULL, NULL, 0, 0);
 914                        printf("%c %s %s\n", sign,
 915                               sha1_to_hex(commit->object.sha1), buf.buf);
 916                        strbuf_release(&buf);
 917                }
 918                else {
 919                        printf("%c %s\n", sign,
 920                               sha1_to_hex(commit->object.sha1));
 921                }
 922
 923                list = list->next;
 924        }
 925
 926        free_patch_ids(&ids);
 927        return 0;
 928}