revision.con commit traverse_commit_list: support pending blobs/trees with paths (2073949)
   1#include "cache.h"
   2#include "tag.h"
   3#include "blob.h"
   4#include "tree.h"
   5#include "commit.h"
   6#include "diff.h"
   7#include "refs.h"
   8#include "revision.h"
   9#include "graph.h"
  10#include "grep.h"
  11#include "reflog-walk.h"
  12#include "patch-ids.h"
  13#include "decorate.h"
  14#include "log-tree.h"
  15#include "string-list.h"
  16#include "line-log.h"
  17#include "mailmap.h"
  18#include "commit-slab.h"
  19#include "dir.h"
  20
  21volatile show_early_output_fn_t show_early_output;
  22
  23char *path_name(const struct name_path *path, const char *name)
  24{
  25        const struct name_path *p;
  26        char *n, *m;
  27        int nlen = strlen(name);
  28        int len = nlen + 1;
  29
  30        for (p = path; p; p = p->up) {
  31                if (p->elem_len)
  32                        len += p->elem_len + 1;
  33        }
  34        n = xmalloc(len);
  35        m = n + len - (nlen + 1);
  36        strcpy(m, name);
  37        for (p = path; p; p = p->up) {
  38                if (p->elem_len) {
  39                        m -= p->elem_len + 1;
  40                        memcpy(m, p->elem, p->elem_len);
  41                        m[p->elem_len] = '/';
  42                }
  43        }
  44        return n;
  45}
  46
  47static int show_path_component_truncated(FILE *out, const char *name, int len)
  48{
  49        int cnt;
  50        for (cnt = 0; cnt < len; cnt++) {
  51                int ch = name[cnt];
  52                if (!ch || ch == '\n')
  53                        return -1;
  54                fputc(ch, out);
  55        }
  56        return len;
  57}
  58
  59static int show_path_truncated(FILE *out, const struct name_path *path)
  60{
  61        int emitted, ours;
  62
  63        if (!path)
  64                return 0;
  65        emitted = show_path_truncated(out, path->up);
  66        if (emitted < 0)
  67                return emitted;
  68        if (emitted)
  69                fputc('/', out);
  70        ours = show_path_component_truncated(out, path->elem, path->elem_len);
  71        if (ours < 0)
  72                return ours;
  73        return ours || emitted;
  74}
  75
  76void show_object_with_name(FILE *out, struct object *obj,
  77                           const struct name_path *path, const char *component)
  78{
  79        struct name_path leaf;
  80        leaf.up = (struct name_path *)path;
  81        leaf.elem = component;
  82        leaf.elem_len = strlen(component);
  83
  84        fprintf(out, "%s ", sha1_to_hex(obj->sha1));
  85        show_path_truncated(out, &leaf);
  86        fputc('\n', out);
  87}
  88
  89void add_object(struct object *obj,
  90                struct object_array *p,
  91                struct name_path *path,
  92                const char *name)
  93{
  94        char *pn = path_name(path, name);
  95        add_object_array(obj, pn, p);
  96        free(pn);
  97}
  98
  99static void mark_blob_uninteresting(struct blob *blob)
 100{
 101        if (!blob)
 102                return;
 103        if (blob->object.flags & UNINTERESTING)
 104                return;
 105        blob->object.flags |= UNINTERESTING;
 106}
 107
 108static void mark_tree_contents_uninteresting(struct tree *tree)
 109{
 110        struct tree_desc desc;
 111        struct name_entry entry;
 112        struct object *obj = &tree->object;
 113
 114        if (!has_sha1_file(obj->sha1))
 115                return;
 116        if (parse_tree(tree) < 0)
 117                die("bad tree %s", sha1_to_hex(obj->sha1));
 118
 119        init_tree_desc(&desc, tree->buffer, tree->size);
 120        while (tree_entry(&desc, &entry)) {
 121                switch (object_type(entry.mode)) {
 122                case OBJ_TREE:
 123                        mark_tree_uninteresting(lookup_tree(entry.sha1));
 124                        break;
 125                case OBJ_BLOB:
 126                        mark_blob_uninteresting(lookup_blob(entry.sha1));
 127                        break;
 128                default:
 129                        /* Subproject commit - not in this repository */
 130                        break;
 131                }
 132        }
 133
 134        /*
 135         * We don't care about the tree any more
 136         * after it has been marked uninteresting.
 137         */
 138        free_tree_buffer(tree);
 139}
 140
 141void mark_tree_uninteresting(struct tree *tree)
 142{
 143        struct object *obj = &tree->object;
 144
 145        if (!tree)
 146                return;
 147        if (obj->flags & UNINTERESTING)
 148                return;
 149        obj->flags |= UNINTERESTING;
 150        mark_tree_contents_uninteresting(tree);
 151}
 152
 153void mark_parents_uninteresting(struct commit *commit)
 154{
 155        struct commit_list *parents = NULL, *l;
 156
 157        for (l = commit->parents; l; l = l->next)
 158                commit_list_insert(l->item, &parents);
 159
 160        while (parents) {
 161                struct commit *commit = parents->item;
 162                l = parents;
 163                parents = parents->next;
 164                free(l);
 165
 166                while (commit) {
 167                        /*
 168                         * A missing commit is ok iff its parent is marked
 169                         * uninteresting.
 170                         *
 171                         * We just mark such a thing parsed, so that when
 172                         * it is popped next time around, we won't be trying
 173                         * to parse it and get an error.
 174                         */
 175                        if (!has_sha1_file(commit->object.sha1))
 176                                commit->object.parsed = 1;
 177
 178                        if (commit->object.flags & UNINTERESTING)
 179                                break;
 180
 181                        commit->object.flags |= UNINTERESTING;
 182
 183                        /*
 184                         * Normally we haven't parsed the parent
 185                         * yet, so we won't have a parent of a parent
 186                         * here. However, it may turn out that we've
 187                         * reached this commit some other way (where it
 188                         * wasn't uninteresting), in which case we need
 189                         * to mark its parents recursively too..
 190                         */
 191                        if (!commit->parents)
 192                                break;
 193
 194                        for (l = commit->parents->next; l; l = l->next)
 195                                commit_list_insert(l->item, &parents);
 196                        commit = commit->parents->item;
 197                }
 198        }
 199}
 200
 201static void add_pending_object_with_path(struct rev_info *revs,
 202                                         struct object *obj,
 203                                         const char *name, unsigned mode,
 204                                         const char *path)
 205{
 206        if (!obj)
 207                return;
 208        if (revs->no_walk && (obj->flags & UNINTERESTING))
 209                revs->no_walk = 0;
 210        if (revs->reflog_info && obj->type == OBJ_COMMIT) {
 211                struct strbuf buf = STRBUF_INIT;
 212                int len = interpret_branch_name(name, 0, &buf);
 213                int st;
 214
 215                if (0 < len && name[len] && buf.len)
 216                        strbuf_addstr(&buf, name + len);
 217                st = add_reflog_for_walk(revs->reflog_info,
 218                                         (struct commit *)obj,
 219                                         buf.buf[0] ? buf.buf: name);
 220                strbuf_release(&buf);
 221                if (st)
 222                        return;
 223        }
 224        add_object_array_with_path(obj, name, &revs->pending, mode, path);
 225}
 226
 227static void add_pending_object_with_mode(struct rev_info *revs,
 228                                         struct object *obj,
 229                                         const char *name, unsigned mode)
 230{
 231        add_pending_object_with_path(revs, obj, name, mode, NULL);
 232}
 233
 234void add_pending_object(struct rev_info *revs,
 235                        struct object *obj, const char *name)
 236{
 237        add_pending_object_with_mode(revs, obj, name, S_IFINVALID);
 238}
 239
 240void add_head_to_pending(struct rev_info *revs)
 241{
 242        unsigned char sha1[20];
 243        struct object *obj;
 244        if (get_sha1("HEAD", sha1))
 245                return;
 246        obj = parse_object(sha1);
 247        if (!obj)
 248                return;
 249        add_pending_object(revs, obj, "HEAD");
 250}
 251
 252static struct object *get_reference(struct rev_info *revs, const char *name,
 253                                    const unsigned char *sha1,
 254                                    unsigned int flags)
 255{
 256        struct object *object;
 257
 258        object = parse_object(sha1);
 259        if (!object) {
 260                if (revs->ignore_missing)
 261                        return object;
 262                die("bad object %s", name);
 263        }
 264        object->flags |= flags;
 265        return object;
 266}
 267
 268void add_pending_sha1(struct rev_info *revs, const char *name,
 269                      const unsigned char *sha1, unsigned int flags)
 270{
 271        struct object *object = get_reference(revs, name, sha1, flags);
 272        add_pending_object(revs, object, name);
 273}
 274
 275static struct commit *handle_commit(struct rev_info *revs,
 276                                    struct object_array_entry *entry)
 277{
 278        struct object *object = entry->item;
 279        const char *name = entry->name;
 280        const char *path = entry->path;
 281        unsigned int mode = entry->mode;
 282        unsigned long flags = object->flags;
 283
 284        /*
 285         * Tag object? Look what it points to..
 286         */
 287        while (object->type == OBJ_TAG) {
 288                struct tag *tag = (struct tag *) object;
 289                if (revs->tag_objects && !(flags & UNINTERESTING))
 290                        add_pending_object(revs, object, tag->tag);
 291                if (!tag->tagged)
 292                        die("bad tag");
 293                object = parse_object(tag->tagged->sha1);
 294                if (!object) {
 295                        if (flags & UNINTERESTING)
 296                                return NULL;
 297                        die("bad object %s", sha1_to_hex(tag->tagged->sha1));
 298                }
 299                object->flags |= flags;
 300                /*
 301                 * We'll handle the tagged object by looping or dropping
 302                 * through to the non-tag handlers below. Do not
 303                 * propagate data from the tag's pending entry.
 304                 */
 305                name = "";
 306                path = NULL;
 307                mode = 0;
 308        }
 309
 310        /*
 311         * Commit object? Just return it, we'll do all the complex
 312         * reachability crud.
 313         */
 314        if (object->type == OBJ_COMMIT) {
 315                struct commit *commit = (struct commit *)object;
 316                if (parse_commit(commit) < 0)
 317                        die("unable to parse commit %s", name);
 318                if (flags & UNINTERESTING) {
 319                        mark_parents_uninteresting(commit);
 320                        revs->limited = 1;
 321                }
 322                if (revs->show_source && !commit->util)
 323                        commit->util = xstrdup(name);
 324                return commit;
 325        }
 326
 327        /*
 328         * Tree object? Either mark it uninteresting, or add it
 329         * to the list of objects to look at later..
 330         */
 331        if (object->type == OBJ_TREE) {
 332                struct tree *tree = (struct tree *)object;
 333                if (!revs->tree_objects)
 334                        return NULL;
 335                if (flags & UNINTERESTING) {
 336                        mark_tree_contents_uninteresting(tree);
 337                        return NULL;
 338                }
 339                add_pending_object_with_path(revs, object, name, mode, path);
 340                return NULL;
 341        }
 342
 343        /*
 344         * Blob object? You know the drill by now..
 345         */
 346        if (object->type == OBJ_BLOB) {
 347                if (!revs->blob_objects)
 348                        return NULL;
 349                if (flags & UNINTERESTING)
 350                        return NULL;
 351                add_pending_object_with_path(revs, object, name, mode, path);
 352                return NULL;
 353        }
 354        die("%s is unknown object", name);
 355}
 356
 357static int everybody_uninteresting(struct commit_list *orig)
 358{
 359        struct commit_list *list = orig;
 360        while (list) {
 361                struct commit *commit = list->item;
 362                list = list->next;
 363                if (commit->object.flags & UNINTERESTING)
 364                        continue;
 365                return 0;
 366        }
 367        return 1;
 368}
 369
 370/*
 371 * A definition of "relevant" commit that we can use to simplify limited graphs
 372 * by eliminating side branches.
 373 *
 374 * A "relevant" commit is one that is !UNINTERESTING (ie we are including it
 375 * in our list), or that is a specified BOTTOM commit. Then after computing
 376 * a limited list, during processing we can generally ignore boundary merges
 377 * coming from outside the graph, (ie from irrelevant parents), and treat
 378 * those merges as if they were single-parent. TREESAME is defined to consider
 379 * only relevant parents, if any. If we are TREESAME to our on-graph parents,
 380 * we don't care if we were !TREESAME to non-graph parents.
 381 *
 382 * Treating bottom commits as relevant ensures that a limited graph's
 383 * connection to the actual bottom commit is not viewed as a side branch, but
 384 * treated as part of the graph. For example:
 385 *
 386 *   ....Z...A---X---o---o---B
 387 *        .     /
 388 *         W---Y
 389 *
 390 * When computing "A..B", the A-X connection is at least as important as
 391 * Y-X, despite A being flagged UNINTERESTING.
 392 *
 393 * And when computing --ancestry-path "A..B", the A-X connection is more
 394 * important than Y-X, despite both A and Y being flagged UNINTERESTING.
 395 */
 396static inline int relevant_commit(struct commit *commit)
 397{
 398        return (commit->object.flags & (UNINTERESTING | BOTTOM)) != UNINTERESTING;
 399}
 400
 401/*
 402 * Return a single relevant commit from a parent list. If we are a TREESAME
 403 * commit, and this selects one of our parents, then we can safely simplify to
 404 * that parent.
 405 */
 406static struct commit *one_relevant_parent(const struct rev_info *revs,
 407                                          struct commit_list *orig)
 408{
 409        struct commit_list *list = orig;
 410        struct commit *relevant = NULL;
 411
 412        if (!orig)
 413                return NULL;
 414
 415        /*
 416         * For 1-parent commits, or if first-parent-only, then return that
 417         * first parent (even if not "relevant" by the above definition).
 418         * TREESAME will have been set purely on that parent.
 419         */
 420        if (revs->first_parent_only || !orig->next)
 421                return orig->item;
 422
 423        /*
 424         * For multi-parent commits, identify a sole relevant parent, if any.
 425         * If we have only one relevant parent, then TREESAME will be set purely
 426         * with regard to that parent, and we can simplify accordingly.
 427         *
 428         * If we have more than one relevant parent, or no relevant parents
 429         * (and multiple irrelevant ones), then we can't select a parent here
 430         * and return NULL.
 431         */
 432        while (list) {
 433                struct commit *commit = list->item;
 434                list = list->next;
 435                if (relevant_commit(commit)) {
 436                        if (relevant)
 437                                return NULL;
 438                        relevant = commit;
 439                }
 440        }
 441        return relevant;
 442}
 443
 444/*
 445 * The goal is to get REV_TREE_NEW as the result only if the
 446 * diff consists of all '+' (and no other changes), REV_TREE_OLD
 447 * if the whole diff is removal of old data, and otherwise
 448 * REV_TREE_DIFFERENT (of course if the trees are the same we
 449 * want REV_TREE_SAME).
 450 * That means that once we get to REV_TREE_DIFFERENT, we do not
 451 * have to look any further.
 452 */
 453static int tree_difference = REV_TREE_SAME;
 454
 455static void file_add_remove(struct diff_options *options,
 456                    int addremove, unsigned mode,
 457                    const unsigned char *sha1,
 458                    int sha1_valid,
 459                    const char *fullpath, unsigned dirty_submodule)
 460{
 461        int diff = addremove == '+' ? REV_TREE_NEW : REV_TREE_OLD;
 462
 463        tree_difference |= diff;
 464        if (tree_difference == REV_TREE_DIFFERENT)
 465                DIFF_OPT_SET(options, HAS_CHANGES);
 466}
 467
 468static void file_change(struct diff_options *options,
 469                 unsigned old_mode, unsigned new_mode,
 470                 const unsigned char *old_sha1,
 471                 const unsigned char *new_sha1,
 472                 int old_sha1_valid, int new_sha1_valid,
 473                 const char *fullpath,
 474                 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
 475{
 476        tree_difference = REV_TREE_DIFFERENT;
 477        DIFF_OPT_SET(options, HAS_CHANGES);
 478}
 479
 480static int rev_compare_tree(struct rev_info *revs,
 481                            struct commit *parent, struct commit *commit)
 482{
 483        struct tree *t1 = parent->tree;
 484        struct tree *t2 = commit->tree;
 485
 486        if (!t1)
 487                return REV_TREE_NEW;
 488        if (!t2)
 489                return REV_TREE_OLD;
 490
 491        if (revs->simplify_by_decoration) {
 492                /*
 493                 * If we are simplifying by decoration, then the commit
 494                 * is worth showing if it has a tag pointing at it.
 495                 */
 496                if (get_name_decoration(&commit->object))
 497                        return REV_TREE_DIFFERENT;
 498                /*
 499                 * A commit that is not pointed by a tag is uninteresting
 500                 * if we are not limited by path.  This means that you will
 501                 * see the usual "commits that touch the paths" plus any
 502                 * tagged commit by specifying both --simplify-by-decoration
 503                 * and pathspec.
 504                 */
 505                if (!revs->prune_data.nr)
 506                        return REV_TREE_SAME;
 507        }
 508
 509        tree_difference = REV_TREE_SAME;
 510        DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
 511        if (diff_tree_sha1(t1->object.sha1, t2->object.sha1, "",
 512                           &revs->pruning) < 0)
 513                return REV_TREE_DIFFERENT;
 514        return tree_difference;
 515}
 516
 517static int rev_same_tree_as_empty(struct rev_info *revs, struct commit *commit)
 518{
 519        int retval;
 520        struct tree *t1 = commit->tree;
 521
 522        if (!t1)
 523                return 0;
 524
 525        tree_difference = REV_TREE_SAME;
 526        DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
 527        retval = diff_tree_sha1(NULL, t1->object.sha1, "", &revs->pruning);
 528
 529        return retval >= 0 && (tree_difference == REV_TREE_SAME);
 530}
 531
 532struct treesame_state {
 533        unsigned int nparents;
 534        unsigned char treesame[FLEX_ARRAY];
 535};
 536
 537static struct treesame_state *initialise_treesame(struct rev_info *revs, struct commit *commit)
 538{
 539        unsigned n = commit_list_count(commit->parents);
 540        struct treesame_state *st = xcalloc(1, sizeof(*st) + n);
 541        st->nparents = n;
 542        add_decoration(&revs->treesame, &commit->object, st);
 543        return st;
 544}
 545
 546/*
 547 * Must be called immediately after removing the nth_parent from a commit's
 548 * parent list, if we are maintaining the per-parent treesame[] decoration.
 549 * This does not recalculate the master TREESAME flag - update_treesame()
 550 * should be called to update it after a sequence of treesame[] modifications
 551 * that may have affected it.
 552 */
 553static int compact_treesame(struct rev_info *revs, struct commit *commit, unsigned nth_parent)
 554{
 555        struct treesame_state *st;
 556        int old_same;
 557
 558        if (!commit->parents) {
 559                /*
 560                 * Have just removed the only parent from a non-merge.
 561                 * Different handling, as we lack decoration.
 562                 */
 563                if (nth_parent != 0)
 564                        die("compact_treesame %u", nth_parent);
 565                old_same = !!(commit->object.flags & TREESAME);
 566                if (rev_same_tree_as_empty(revs, commit))
 567                        commit->object.flags |= TREESAME;
 568                else
 569                        commit->object.flags &= ~TREESAME;
 570                return old_same;
 571        }
 572
 573        st = lookup_decoration(&revs->treesame, &commit->object);
 574        if (!st || nth_parent >= st->nparents)
 575                die("compact_treesame %u", nth_parent);
 576
 577        old_same = st->treesame[nth_parent];
 578        memmove(st->treesame + nth_parent,
 579                st->treesame + nth_parent + 1,
 580                st->nparents - nth_parent - 1);
 581
 582        /*
 583         * If we've just become a non-merge commit, update TREESAME
 584         * immediately, and remove the no-longer-needed decoration.
 585         * If still a merge, defer update until update_treesame().
 586         */
 587        if (--st->nparents == 1) {
 588                if (commit->parents->next)
 589                        die("compact_treesame parents mismatch");
 590                if (st->treesame[0] && revs->dense)
 591                        commit->object.flags |= TREESAME;
 592                else
 593                        commit->object.flags &= ~TREESAME;
 594                free(add_decoration(&revs->treesame, &commit->object, NULL));
 595        }
 596
 597        return old_same;
 598}
 599
 600static unsigned update_treesame(struct rev_info *revs, struct commit *commit)
 601{
 602        if (commit->parents && commit->parents->next) {
 603                unsigned n;
 604                struct treesame_state *st;
 605                struct commit_list *p;
 606                unsigned relevant_parents;
 607                unsigned relevant_change, irrelevant_change;
 608
 609                st = lookup_decoration(&revs->treesame, &commit->object);
 610                if (!st)
 611                        die("update_treesame %s", sha1_to_hex(commit->object.sha1));
 612                relevant_parents = 0;
 613                relevant_change = irrelevant_change = 0;
 614                for (p = commit->parents, n = 0; p; n++, p = p->next) {
 615                        if (relevant_commit(p->item)) {
 616                                relevant_change |= !st->treesame[n];
 617                                relevant_parents++;
 618                        } else
 619                                irrelevant_change |= !st->treesame[n];
 620                }
 621                if (relevant_parents ? relevant_change : irrelevant_change)
 622                        commit->object.flags &= ~TREESAME;
 623                else
 624                        commit->object.flags |= TREESAME;
 625        }
 626
 627        return commit->object.flags & TREESAME;
 628}
 629
 630static inline int limiting_can_increase_treesame(const struct rev_info *revs)
 631{
 632        /*
 633         * TREESAME is irrelevant unless prune && dense;
 634         * if simplify_history is set, we can't have a mixture of TREESAME and
 635         *    !TREESAME INTERESTING parents (and we don't have treesame[]
 636         *    decoration anyway);
 637         * if first_parent_only is set, then the TREESAME flag is locked
 638         *    against the first parent (and again we lack treesame[] decoration).
 639         */
 640        return revs->prune && revs->dense &&
 641               !revs->simplify_history &&
 642               !revs->first_parent_only;
 643}
 644
 645static void try_to_simplify_commit(struct rev_info *revs, struct commit *commit)
 646{
 647        struct commit_list **pp, *parent;
 648        struct treesame_state *ts = NULL;
 649        int relevant_change = 0, irrelevant_change = 0;
 650        int relevant_parents, nth_parent;
 651
 652        /*
 653         * If we don't do pruning, everything is interesting
 654         */
 655        if (!revs->prune)
 656                return;
 657
 658        if (!commit->tree)
 659                return;
 660
 661        if (!commit->parents) {
 662                if (rev_same_tree_as_empty(revs, commit))
 663                        commit->object.flags |= TREESAME;
 664                return;
 665        }
 666
 667        /*
 668         * Normal non-merge commit? If we don't want to make the
 669         * history dense, we consider it always to be a change..
 670         */
 671        if (!revs->dense && !commit->parents->next)
 672                return;
 673
 674        for (pp = &commit->parents, nth_parent = 0, relevant_parents = 0;
 675             (parent = *pp) != NULL;
 676             pp = &parent->next, nth_parent++) {
 677                struct commit *p = parent->item;
 678                if (relevant_commit(p))
 679                        relevant_parents++;
 680
 681                if (nth_parent == 1) {
 682                        /*
 683                         * This our second loop iteration - so we now know
 684                         * we're dealing with a merge.
 685                         *
 686                         * Do not compare with later parents when we care only about
 687                         * the first parent chain, in order to avoid derailing the
 688                         * traversal to follow a side branch that brought everything
 689                         * in the path we are limited to by the pathspec.
 690                         */
 691                        if (revs->first_parent_only)
 692                                break;
 693                        /*
 694                         * If this will remain a potentially-simplifiable
 695                         * merge, remember per-parent treesame if needed.
 696                         * Initialise the array with the comparison from our
 697                         * first iteration.
 698                         */
 699                        if (revs->treesame.name &&
 700                            !revs->simplify_history &&
 701                            !(commit->object.flags & UNINTERESTING)) {
 702                                ts = initialise_treesame(revs, commit);
 703                                if (!(irrelevant_change || relevant_change))
 704                                        ts->treesame[0] = 1;
 705                        }
 706                }
 707                if (parse_commit(p) < 0)
 708                        die("cannot simplify commit %s (because of %s)",
 709                            sha1_to_hex(commit->object.sha1),
 710                            sha1_to_hex(p->object.sha1));
 711                switch (rev_compare_tree(revs, p, commit)) {
 712                case REV_TREE_SAME:
 713                        if (!revs->simplify_history || !relevant_commit(p)) {
 714                                /* Even if a merge with an uninteresting
 715                                 * side branch brought the entire change
 716                                 * we are interested in, we do not want
 717                                 * to lose the other branches of this
 718                                 * merge, so we just keep going.
 719                                 */
 720                                if (ts)
 721                                        ts->treesame[nth_parent] = 1;
 722                                continue;
 723                        }
 724                        parent->next = NULL;
 725                        commit->parents = parent;
 726                        commit->object.flags |= TREESAME;
 727                        return;
 728
 729                case REV_TREE_NEW:
 730                        if (revs->remove_empty_trees &&
 731                            rev_same_tree_as_empty(revs, p)) {
 732                                /* We are adding all the specified
 733                                 * paths from this parent, so the
 734                                 * history beyond this parent is not
 735                                 * interesting.  Remove its parents
 736                                 * (they are grandparents for us).
 737                                 * IOW, we pretend this parent is a
 738                                 * "root" commit.
 739                                 */
 740                                if (parse_commit(p) < 0)
 741                                        die("cannot simplify commit %s (invalid %s)",
 742                                            sha1_to_hex(commit->object.sha1),
 743                                            sha1_to_hex(p->object.sha1));
 744                                p->parents = NULL;
 745                        }
 746                /* fallthrough */
 747                case REV_TREE_OLD:
 748                case REV_TREE_DIFFERENT:
 749                        if (relevant_commit(p))
 750                                relevant_change = 1;
 751                        else
 752                                irrelevant_change = 1;
 753                        continue;
 754                }
 755                die("bad tree compare for commit %s", sha1_to_hex(commit->object.sha1));
 756        }
 757
 758        /*
 759         * TREESAME is straightforward for single-parent commits. For merge
 760         * commits, it is most useful to define it so that "irrelevant"
 761         * parents cannot make us !TREESAME - if we have any relevant
 762         * parents, then we only consider TREESAMEness with respect to them,
 763         * allowing irrelevant merges from uninteresting branches to be
 764         * simplified away. Only if we have only irrelevant parents do we
 765         * base TREESAME on them. Note that this logic is replicated in
 766         * update_treesame, which should be kept in sync.
 767         */
 768        if (relevant_parents ? !relevant_change : !irrelevant_change)
 769                commit->object.flags |= TREESAME;
 770}
 771
 772static void commit_list_insert_by_date_cached(struct commit *p, struct commit_list **head,
 773                    struct commit_list *cached_base, struct commit_list **cache)
 774{
 775        struct commit_list *new_entry;
 776
 777        if (cached_base && p->date < cached_base->item->date)
 778                new_entry = commit_list_insert_by_date(p, &cached_base->next);
 779        else
 780                new_entry = commit_list_insert_by_date(p, head);
 781
 782        if (cache && (!*cache || p->date < (*cache)->item->date))
 783                *cache = new_entry;
 784}
 785
 786static int add_parents_to_list(struct rev_info *revs, struct commit *commit,
 787                    struct commit_list **list, struct commit_list **cache_ptr)
 788{
 789        struct commit_list *parent = commit->parents;
 790        unsigned left_flag;
 791        struct commit_list *cached_base = cache_ptr ? *cache_ptr : NULL;
 792
 793        if (commit->object.flags & ADDED)
 794                return 0;
 795        commit->object.flags |= ADDED;
 796
 797        if (revs->include_check &&
 798            !revs->include_check(commit, revs->include_check_data))
 799                return 0;
 800
 801        /*
 802         * If the commit is uninteresting, don't try to
 803         * prune parents - we want the maximal uninteresting
 804         * set.
 805         *
 806         * Normally we haven't parsed the parent
 807         * yet, so we won't have a parent of a parent
 808         * here. However, it may turn out that we've
 809         * reached this commit some other way (where it
 810         * wasn't uninteresting), in which case we need
 811         * to mark its parents recursively too..
 812         */
 813        if (commit->object.flags & UNINTERESTING) {
 814                while (parent) {
 815                        struct commit *p = parent->item;
 816                        parent = parent->next;
 817                        if (p)
 818                                p->object.flags |= UNINTERESTING;
 819                        if (parse_commit(p) < 0)
 820                                continue;
 821                        if (p->parents)
 822                                mark_parents_uninteresting(p);
 823                        if (p->object.flags & SEEN)
 824                                continue;
 825                        p->object.flags |= SEEN;
 826                        commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
 827                }
 828                return 0;
 829        }
 830
 831        /*
 832         * Ok, the commit wasn't uninteresting. Try to
 833         * simplify the commit history and find the parent
 834         * that has no differences in the path set if one exists.
 835         */
 836        try_to_simplify_commit(revs, commit);
 837
 838        if (revs->no_walk)
 839                return 0;
 840
 841        left_flag = (commit->object.flags & SYMMETRIC_LEFT);
 842
 843        for (parent = commit->parents; parent; parent = parent->next) {
 844                struct commit *p = parent->item;
 845
 846                if (parse_commit(p) < 0)
 847                        return -1;
 848                if (revs->show_source && !p->util)
 849                        p->util = commit->util;
 850                p->object.flags |= left_flag;
 851                if (!(p->object.flags & SEEN)) {
 852                        p->object.flags |= SEEN;
 853                        commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
 854                }
 855                if (revs->first_parent_only)
 856                        break;
 857        }
 858        return 0;
 859}
 860
 861static void cherry_pick_list(struct commit_list *list, struct rev_info *revs)
 862{
 863        struct commit_list *p;
 864        int left_count = 0, right_count = 0;
 865        int left_first;
 866        struct patch_ids ids;
 867        unsigned cherry_flag;
 868
 869        /* First count the commits on the left and on the right */
 870        for (p = list; p; p = p->next) {
 871                struct commit *commit = p->item;
 872                unsigned flags = commit->object.flags;
 873                if (flags & BOUNDARY)
 874                        ;
 875                else if (flags & SYMMETRIC_LEFT)
 876                        left_count++;
 877                else
 878                        right_count++;
 879        }
 880
 881        if (!left_count || !right_count)
 882                return;
 883
 884        left_first = left_count < right_count;
 885        init_patch_ids(&ids);
 886        ids.diffopts.pathspec = revs->diffopt.pathspec;
 887
 888        /* Compute patch-ids for one side */
 889        for (p = list; p; p = p->next) {
 890                struct commit *commit = p->item;
 891                unsigned flags = commit->object.flags;
 892
 893                if (flags & BOUNDARY)
 894                        continue;
 895                /*
 896                 * If we have fewer left, left_first is set and we omit
 897                 * commits on the right branch in this loop.  If we have
 898                 * fewer right, we skip the left ones.
 899                 */
 900                if (left_first != !!(flags & SYMMETRIC_LEFT))
 901                        continue;
 902                commit->util = add_commit_patch_id(commit, &ids);
 903        }
 904
 905        /* either cherry_mark or cherry_pick are true */
 906        cherry_flag = revs->cherry_mark ? PATCHSAME : SHOWN;
 907
 908        /* Check the other side */
 909        for (p = list; p; p = p->next) {
 910                struct commit *commit = p->item;
 911                struct patch_id *id;
 912                unsigned flags = commit->object.flags;
 913
 914                if (flags & BOUNDARY)
 915                        continue;
 916                /*
 917                 * If we have fewer left, left_first is set and we omit
 918                 * commits on the left branch in this loop.
 919                 */
 920                if (left_first == !!(flags & SYMMETRIC_LEFT))
 921                        continue;
 922
 923                /*
 924                 * Have we seen the same patch id?
 925                 */
 926                id = has_commit_patch_id(commit, &ids);
 927                if (!id)
 928                        continue;
 929                id->seen = 1;
 930                commit->object.flags |= cherry_flag;
 931        }
 932
 933        /* Now check the original side for seen ones */
 934        for (p = list; p; p = p->next) {
 935                struct commit *commit = p->item;
 936                struct patch_id *ent;
 937
 938                ent = commit->util;
 939                if (!ent)
 940                        continue;
 941                if (ent->seen)
 942                        commit->object.flags |= cherry_flag;
 943                commit->util = NULL;
 944        }
 945
 946        free_patch_ids(&ids);
 947}
 948
 949/* How many extra uninteresting commits we want to see.. */
 950#define SLOP 5
 951
 952static int still_interesting(struct commit_list *src, unsigned long date, int slop)
 953{
 954        /*
 955         * No source list at all? We're definitely done..
 956         */
 957        if (!src)
 958                return 0;
 959
 960        /*
 961         * Does the destination list contain entries with a date
 962         * before the source list? Definitely _not_ done.
 963         */
 964        if (date <= src->item->date)
 965                return SLOP;
 966
 967        /*
 968         * Does the source list still have interesting commits in
 969         * it? Definitely not done..
 970         */
 971        if (!everybody_uninteresting(src))
 972                return SLOP;
 973
 974        /* Ok, we're closing in.. */
 975        return slop-1;
 976}
 977
 978/*
 979 * "rev-list --ancestry-path A..B" computes commits that are ancestors
 980 * of B but not ancestors of A but further limits the result to those
 981 * that are descendants of A.  This takes the list of bottom commits and
 982 * the result of "A..B" without --ancestry-path, and limits the latter
 983 * further to the ones that can reach one of the commits in "bottom".
 984 */
 985static void limit_to_ancestry(struct commit_list *bottom, struct commit_list *list)
 986{
 987        struct commit_list *p;
 988        struct commit_list *rlist = NULL;
 989        int made_progress;
 990
 991        /*
 992         * Reverse the list so that it will be likely that we would
 993         * process parents before children.
 994         */
 995        for (p = list; p; p = p->next)
 996                commit_list_insert(p->item, &rlist);
 997
 998        for (p = bottom; p; p = p->next)
 999                p->item->object.flags |= TMP_MARK;
1000
1001        /*
1002         * Mark the ones that can reach bottom commits in "list",
1003         * in a bottom-up fashion.
1004         */
1005        do {
1006                made_progress = 0;
1007                for (p = rlist; p; p = p->next) {
1008                        struct commit *c = p->item;
1009                        struct commit_list *parents;
1010                        if (c->object.flags & (TMP_MARK | UNINTERESTING))
1011                                continue;
1012                        for (parents = c->parents;
1013                             parents;
1014                             parents = parents->next) {
1015                                if (!(parents->item->object.flags & TMP_MARK))
1016                                        continue;
1017                                c->object.flags |= TMP_MARK;
1018                                made_progress = 1;
1019                                break;
1020                        }
1021                }
1022        } while (made_progress);
1023
1024        /*
1025         * NEEDSWORK: decide if we want to remove parents that are
1026         * not marked with TMP_MARK from commit->parents for commits
1027         * in the resulting list.  We may not want to do that, though.
1028         */
1029
1030        /*
1031         * The ones that are not marked with TMP_MARK are uninteresting
1032         */
1033        for (p = list; p; p = p->next) {
1034                struct commit *c = p->item;
1035                if (c->object.flags & TMP_MARK)
1036                        continue;
1037                c->object.flags |= UNINTERESTING;
1038        }
1039
1040        /* We are done with the TMP_MARK */
1041        for (p = list; p; p = p->next)
1042                p->item->object.flags &= ~TMP_MARK;
1043        for (p = bottom; p; p = p->next)
1044                p->item->object.flags &= ~TMP_MARK;
1045        free_commit_list(rlist);
1046}
1047
1048/*
1049 * Before walking the history, keep the set of "negative" refs the
1050 * caller has asked to exclude.
1051 *
1052 * This is used to compute "rev-list --ancestry-path A..B", as we need
1053 * to filter the result of "A..B" further to the ones that can actually
1054 * reach A.
1055 */
1056static struct commit_list *collect_bottom_commits(struct commit_list *list)
1057{
1058        struct commit_list *elem, *bottom = NULL;
1059        for (elem = list; elem; elem = elem->next)
1060                if (elem->item->object.flags & BOTTOM)
1061                        commit_list_insert(elem->item, &bottom);
1062        return bottom;
1063}
1064
1065/* Assumes either left_only or right_only is set */
1066static void limit_left_right(struct commit_list *list, struct rev_info *revs)
1067{
1068        struct commit_list *p;
1069
1070        for (p = list; p; p = p->next) {
1071                struct commit *commit = p->item;
1072
1073                if (revs->right_only) {
1074                        if (commit->object.flags & SYMMETRIC_LEFT)
1075                                commit->object.flags |= SHOWN;
1076                } else  /* revs->left_only is set */
1077                        if (!(commit->object.flags & SYMMETRIC_LEFT))
1078                                commit->object.flags |= SHOWN;
1079        }
1080}
1081
1082static int limit_list(struct rev_info *revs)
1083{
1084        int slop = SLOP;
1085        unsigned long date = ~0ul;
1086        struct commit_list *list = revs->commits;
1087        struct commit_list *newlist = NULL;
1088        struct commit_list **p = &newlist;
1089        struct commit_list *bottom = NULL;
1090
1091        if (revs->ancestry_path) {
1092                bottom = collect_bottom_commits(list);
1093                if (!bottom)
1094                        die("--ancestry-path given but there are no bottom commits");
1095        }
1096
1097        while (list) {
1098                struct commit_list *entry = list;
1099                struct commit *commit = list->item;
1100                struct object *obj = &commit->object;
1101                show_early_output_fn_t show;
1102
1103                list = list->next;
1104                free(entry);
1105
1106                if (revs->max_age != -1 && (commit->date < revs->max_age))
1107                        obj->flags |= UNINTERESTING;
1108                if (add_parents_to_list(revs, commit, &list, NULL) < 0)
1109                        return -1;
1110                if (obj->flags & UNINTERESTING) {
1111                        mark_parents_uninteresting(commit);
1112                        if (revs->show_all)
1113                                p = &commit_list_insert(commit, p)->next;
1114                        slop = still_interesting(list, date, slop);
1115                        if (slop)
1116                                continue;
1117                        /* If showing all, add the whole pending list to the end */
1118                        if (revs->show_all)
1119                                *p = list;
1120                        break;
1121                }
1122                if (revs->min_age != -1 && (commit->date > revs->min_age))
1123                        continue;
1124                date = commit->date;
1125                p = &commit_list_insert(commit, p)->next;
1126
1127                show = show_early_output;
1128                if (!show)
1129                        continue;
1130
1131                show(revs, newlist);
1132                show_early_output = NULL;
1133        }
1134        if (revs->cherry_pick || revs->cherry_mark)
1135                cherry_pick_list(newlist, revs);
1136
1137        if (revs->left_only || revs->right_only)
1138                limit_left_right(newlist, revs);
1139
1140        if (bottom) {
1141                limit_to_ancestry(bottom, newlist);
1142                free_commit_list(bottom);
1143        }
1144
1145        /*
1146         * Check if any commits have become TREESAME by some of their parents
1147         * becoming UNINTERESTING.
1148         */
1149        if (limiting_can_increase_treesame(revs))
1150                for (list = newlist; list; list = list->next) {
1151                        struct commit *c = list->item;
1152                        if (c->object.flags & (UNINTERESTING | TREESAME))
1153                                continue;
1154                        update_treesame(revs, c);
1155                }
1156
1157        revs->commits = newlist;
1158        return 0;
1159}
1160
1161/*
1162 * Add an entry to refs->cmdline with the specified information.
1163 * *name is copied.
1164 */
1165static void add_rev_cmdline(struct rev_info *revs,
1166                            struct object *item,
1167                            const char *name,
1168                            int whence,
1169                            unsigned flags)
1170{
1171        struct rev_cmdline_info *info = &revs->cmdline;
1172        int nr = info->nr;
1173
1174        ALLOC_GROW(info->rev, nr + 1, info->alloc);
1175        info->rev[nr].item = item;
1176        info->rev[nr].name = xstrdup(name);
1177        info->rev[nr].whence = whence;
1178        info->rev[nr].flags = flags;
1179        info->nr++;
1180}
1181
1182static void add_rev_cmdline_list(struct rev_info *revs,
1183                                 struct commit_list *commit_list,
1184                                 int whence,
1185                                 unsigned flags)
1186{
1187        while (commit_list) {
1188                struct object *object = &commit_list->item->object;
1189                add_rev_cmdline(revs, object, sha1_to_hex(object->sha1),
1190                                whence, flags);
1191                commit_list = commit_list->next;
1192        }
1193}
1194
1195struct all_refs_cb {
1196        int all_flags;
1197        int warned_bad_reflog;
1198        struct rev_info *all_revs;
1199        const char *name_for_errormsg;
1200};
1201
1202int ref_excluded(struct string_list *ref_excludes, const char *path)
1203{
1204        struct string_list_item *item;
1205
1206        if (!ref_excludes)
1207                return 0;
1208        for_each_string_list_item(item, ref_excludes) {
1209                if (!wildmatch(item->string, path, 0, NULL))
1210                        return 1;
1211        }
1212        return 0;
1213}
1214
1215static int handle_one_ref(const char *path, const unsigned char *sha1, int flag, void *cb_data)
1216{
1217        struct all_refs_cb *cb = cb_data;
1218        struct object *object;
1219
1220        if (ref_excluded(cb->all_revs->ref_excludes, path))
1221            return 0;
1222
1223        object = get_reference(cb->all_revs, path, sha1, cb->all_flags);
1224        add_rev_cmdline(cb->all_revs, object, path, REV_CMD_REF, cb->all_flags);
1225        add_pending_sha1(cb->all_revs, path, sha1, cb->all_flags);
1226        return 0;
1227}
1228
1229static void init_all_refs_cb(struct all_refs_cb *cb, struct rev_info *revs,
1230        unsigned flags)
1231{
1232        cb->all_revs = revs;
1233        cb->all_flags = flags;
1234}
1235
1236void clear_ref_exclusion(struct string_list **ref_excludes_p)
1237{
1238        if (*ref_excludes_p) {
1239                string_list_clear(*ref_excludes_p, 0);
1240                free(*ref_excludes_p);
1241        }
1242        *ref_excludes_p = NULL;
1243}
1244
1245void add_ref_exclusion(struct string_list **ref_excludes_p, const char *exclude)
1246{
1247        if (!*ref_excludes_p) {
1248                *ref_excludes_p = xcalloc(1, sizeof(**ref_excludes_p));
1249                (*ref_excludes_p)->strdup_strings = 1;
1250        }
1251        string_list_append(*ref_excludes_p, exclude);
1252}
1253
1254static void handle_refs(const char *submodule, struct rev_info *revs, unsigned flags,
1255                int (*for_each)(const char *, each_ref_fn, void *))
1256{
1257        struct all_refs_cb cb;
1258        init_all_refs_cb(&cb, revs, flags);
1259        for_each(submodule, handle_one_ref, &cb);
1260}
1261
1262static void handle_one_reflog_commit(unsigned char *sha1, void *cb_data)
1263{
1264        struct all_refs_cb *cb = cb_data;
1265        if (!is_null_sha1(sha1)) {
1266                struct object *o = parse_object(sha1);
1267                if (o) {
1268                        o->flags |= cb->all_flags;
1269                        /* ??? CMDLINEFLAGS ??? */
1270                        add_pending_object(cb->all_revs, o, "");
1271                }
1272                else if (!cb->warned_bad_reflog) {
1273                        warning("reflog of '%s' references pruned commits",
1274                                cb->name_for_errormsg);
1275                        cb->warned_bad_reflog = 1;
1276                }
1277        }
1278}
1279
1280static int handle_one_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
1281                const char *email, unsigned long timestamp, int tz,
1282                const char *message, void *cb_data)
1283{
1284        handle_one_reflog_commit(osha1, cb_data);
1285        handle_one_reflog_commit(nsha1, cb_data);
1286        return 0;
1287}
1288
1289static int handle_one_reflog(const char *path, const unsigned char *sha1, int flag, void *cb_data)
1290{
1291        struct all_refs_cb *cb = cb_data;
1292        cb->warned_bad_reflog = 0;
1293        cb->name_for_errormsg = path;
1294        for_each_reflog_ent(path, handle_one_reflog_ent, cb_data);
1295        return 0;
1296}
1297
1298void add_reflogs_to_pending(struct rev_info *revs, unsigned flags)
1299{
1300        struct all_refs_cb cb;
1301        cb.all_revs = revs;
1302        cb.all_flags = flags;
1303        for_each_reflog(handle_one_reflog, &cb);
1304}
1305
1306static int add_parents_only(struct rev_info *revs, const char *arg_, int flags)
1307{
1308        unsigned char sha1[20];
1309        struct object *it;
1310        struct commit *commit;
1311        struct commit_list *parents;
1312        const char *arg = arg_;
1313
1314        if (*arg == '^') {
1315                flags ^= UNINTERESTING | BOTTOM;
1316                arg++;
1317        }
1318        if (get_sha1_committish(arg, sha1))
1319                return 0;
1320        while (1) {
1321                it = get_reference(revs, arg, sha1, 0);
1322                if (!it && revs->ignore_missing)
1323                        return 0;
1324                if (it->type != OBJ_TAG)
1325                        break;
1326                if (!((struct tag*)it)->tagged)
1327                        return 0;
1328                hashcpy(sha1, ((struct tag*)it)->tagged->sha1);
1329        }
1330        if (it->type != OBJ_COMMIT)
1331                return 0;
1332        commit = (struct commit *)it;
1333        for (parents = commit->parents; parents; parents = parents->next) {
1334                it = &parents->item->object;
1335                it->flags |= flags;
1336                add_rev_cmdline(revs, it, arg_, REV_CMD_PARENTS_ONLY, flags);
1337                add_pending_object(revs, it, arg);
1338        }
1339        return 1;
1340}
1341
1342void init_revisions(struct rev_info *revs, const char *prefix)
1343{
1344        memset(revs, 0, sizeof(*revs));
1345
1346        revs->abbrev = DEFAULT_ABBREV;
1347        revs->ignore_merges = 1;
1348        revs->simplify_history = 1;
1349        DIFF_OPT_SET(&revs->pruning, RECURSIVE);
1350        DIFF_OPT_SET(&revs->pruning, QUICK);
1351        revs->pruning.add_remove = file_add_remove;
1352        revs->pruning.change = file_change;
1353        revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
1354        revs->dense = 1;
1355        revs->prefix = prefix;
1356        revs->max_age = -1;
1357        revs->min_age = -1;
1358        revs->skip_count = -1;
1359        revs->max_count = -1;
1360        revs->max_parents = -1;
1361
1362        revs->commit_format = CMIT_FMT_DEFAULT;
1363
1364        init_grep_defaults();
1365        grep_init(&revs->grep_filter, prefix);
1366        revs->grep_filter.status_only = 1;
1367        revs->grep_filter.regflags = REG_NEWLINE;
1368
1369        diff_setup(&revs->diffopt);
1370        if (prefix && !revs->diffopt.prefix) {
1371                revs->diffopt.prefix = prefix;
1372                revs->diffopt.prefix_length = strlen(prefix);
1373        }
1374
1375        revs->notes_opt.use_default_notes = -1;
1376}
1377
1378static void add_pending_commit_list(struct rev_info *revs,
1379                                    struct commit_list *commit_list,
1380                                    unsigned int flags)
1381{
1382        while (commit_list) {
1383                struct object *object = &commit_list->item->object;
1384                object->flags |= flags;
1385                add_pending_object(revs, object, sha1_to_hex(object->sha1));
1386                commit_list = commit_list->next;
1387        }
1388}
1389
1390static void prepare_show_merge(struct rev_info *revs)
1391{
1392        struct commit_list *bases;
1393        struct commit *head, *other;
1394        unsigned char sha1[20];
1395        const char **prune = NULL;
1396        int i, prune_num = 1; /* counting terminating NULL */
1397
1398        if (get_sha1("HEAD", sha1))
1399                die("--merge without HEAD?");
1400        head = lookup_commit_or_die(sha1, "HEAD");
1401        if (get_sha1("MERGE_HEAD", sha1))
1402                die("--merge without MERGE_HEAD?");
1403        other = lookup_commit_or_die(sha1, "MERGE_HEAD");
1404        add_pending_object(revs, &head->object, "HEAD");
1405        add_pending_object(revs, &other->object, "MERGE_HEAD");
1406        bases = get_merge_bases(head, other, 1);
1407        add_rev_cmdline_list(revs, bases, REV_CMD_MERGE_BASE, UNINTERESTING | BOTTOM);
1408        add_pending_commit_list(revs, bases, UNINTERESTING | BOTTOM);
1409        free_commit_list(bases);
1410        head->object.flags |= SYMMETRIC_LEFT;
1411
1412        if (!active_nr)
1413                read_cache();
1414        for (i = 0; i < active_nr; i++) {
1415                const struct cache_entry *ce = active_cache[i];
1416                if (!ce_stage(ce))
1417                        continue;
1418                if (ce_path_match(ce, &revs->prune_data, NULL)) {
1419                        prune_num++;
1420                        REALLOC_ARRAY(prune, prune_num);
1421                        prune[prune_num-2] = ce->name;
1422                        prune[prune_num-1] = NULL;
1423                }
1424                while ((i+1 < active_nr) &&
1425                       ce_same_name(ce, active_cache[i+1]))
1426                        i++;
1427        }
1428        free_pathspec(&revs->prune_data);
1429        parse_pathspec(&revs->prune_data, PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1430                       PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH, "", prune);
1431        revs->limited = 1;
1432}
1433
1434int handle_revision_arg(const char *arg_, struct rev_info *revs, int flags, unsigned revarg_opt)
1435{
1436        struct object_context oc;
1437        char *dotdot;
1438        struct object *object;
1439        unsigned char sha1[20];
1440        int local_flags;
1441        const char *arg = arg_;
1442        int cant_be_filename = revarg_opt & REVARG_CANNOT_BE_FILENAME;
1443        unsigned get_sha1_flags = 0;
1444
1445        flags = flags & UNINTERESTING ? flags | BOTTOM : flags & ~BOTTOM;
1446
1447        dotdot = strstr(arg, "..");
1448        if (dotdot) {
1449                unsigned char from_sha1[20];
1450                const char *next = dotdot + 2;
1451                const char *this = arg;
1452                int symmetric = *next == '.';
1453                unsigned int flags_exclude = flags ^ (UNINTERESTING | BOTTOM);
1454                static const char head_by_default[] = "HEAD";
1455                unsigned int a_flags;
1456
1457                *dotdot = 0;
1458                next += symmetric;
1459
1460                if (!*next)
1461                        next = head_by_default;
1462                if (dotdot == arg)
1463                        this = head_by_default;
1464                if (this == head_by_default && next == head_by_default &&
1465                    !symmetric) {
1466                        /*
1467                         * Just ".."?  That is not a range but the
1468                         * pathspec for the parent directory.
1469                         */
1470                        if (!cant_be_filename) {
1471                                *dotdot = '.';
1472                                return -1;
1473                        }
1474                }
1475                if (!get_sha1_committish(this, from_sha1) &&
1476                    !get_sha1_committish(next, sha1)) {
1477                        struct object *a_obj, *b_obj;
1478
1479                        if (!cant_be_filename) {
1480                                *dotdot = '.';
1481                                verify_non_filename(revs->prefix, arg);
1482                        }
1483
1484                        a_obj = parse_object(from_sha1);
1485                        b_obj = parse_object(sha1);
1486                        if (!a_obj || !b_obj) {
1487                        missing:
1488                                if (revs->ignore_missing)
1489                                        return 0;
1490                                die(symmetric
1491                                    ? "Invalid symmetric difference expression %s"
1492                                    : "Invalid revision range %s", arg);
1493                        }
1494
1495                        if (!symmetric) {
1496                                /* just A..B */
1497                                a_flags = flags_exclude;
1498                        } else {
1499                                /* A...B -- find merge bases between the two */
1500                                struct commit *a, *b;
1501                                struct commit_list *exclude;
1502
1503                                a = (a_obj->type == OBJ_COMMIT
1504                                     ? (struct commit *)a_obj
1505                                     : lookup_commit_reference(a_obj->sha1));
1506                                b = (b_obj->type == OBJ_COMMIT
1507                                     ? (struct commit *)b_obj
1508                                     : lookup_commit_reference(b_obj->sha1));
1509                                if (!a || !b)
1510                                        goto missing;
1511                                exclude = get_merge_bases(a, b, 1);
1512                                add_rev_cmdline_list(revs, exclude,
1513                                                     REV_CMD_MERGE_BASE,
1514                                                     flags_exclude);
1515                                add_pending_commit_list(revs, exclude,
1516                                                        flags_exclude);
1517                                free_commit_list(exclude);
1518
1519                                a_flags = flags | SYMMETRIC_LEFT;
1520                        }
1521
1522                        a_obj->flags |= a_flags;
1523                        b_obj->flags |= flags;
1524                        add_rev_cmdline(revs, a_obj, this,
1525                                        REV_CMD_LEFT, a_flags);
1526                        add_rev_cmdline(revs, b_obj, next,
1527                                        REV_CMD_RIGHT, flags);
1528                        add_pending_object(revs, a_obj, this);
1529                        add_pending_object(revs, b_obj, next);
1530                        return 0;
1531                }
1532                *dotdot = '.';
1533        }
1534        dotdot = strstr(arg, "^@");
1535        if (dotdot && !dotdot[2]) {
1536                *dotdot = 0;
1537                if (add_parents_only(revs, arg, flags))
1538                        return 0;
1539                *dotdot = '^';
1540        }
1541        dotdot = strstr(arg, "^!");
1542        if (dotdot && !dotdot[2]) {
1543                *dotdot = 0;
1544                if (!add_parents_only(revs, arg, flags ^ (UNINTERESTING | BOTTOM)))
1545                        *dotdot = '^';
1546        }
1547
1548        local_flags = 0;
1549        if (*arg == '^') {
1550                local_flags = UNINTERESTING | BOTTOM;
1551                arg++;
1552        }
1553
1554        if (revarg_opt & REVARG_COMMITTISH)
1555                get_sha1_flags = GET_SHA1_COMMITTISH;
1556
1557        if (get_sha1_with_context(arg, get_sha1_flags, sha1, &oc))
1558                return revs->ignore_missing ? 0 : -1;
1559        if (!cant_be_filename)
1560                verify_non_filename(revs->prefix, arg);
1561        object = get_reference(revs, arg, sha1, flags ^ local_flags);
1562        add_rev_cmdline(revs, object, arg_, REV_CMD_REV, flags ^ local_flags);
1563        add_pending_object_with_mode(revs, object, arg, oc.mode);
1564        return 0;
1565}
1566
1567struct cmdline_pathspec {
1568        int alloc;
1569        int nr;
1570        const char **path;
1571};
1572
1573static void append_prune_data(struct cmdline_pathspec *prune, const char **av)
1574{
1575        while (*av) {
1576                ALLOC_GROW(prune->path, prune->nr + 1, prune->alloc);
1577                prune->path[prune->nr++] = *(av++);
1578        }
1579}
1580
1581static void read_pathspec_from_stdin(struct rev_info *revs, struct strbuf *sb,
1582                                     struct cmdline_pathspec *prune)
1583{
1584        while (strbuf_getwholeline(sb, stdin, '\n') != EOF) {
1585                int len = sb->len;
1586                if (len && sb->buf[len - 1] == '\n')
1587                        sb->buf[--len] = '\0';
1588                ALLOC_GROW(prune->path, prune->nr + 1, prune->alloc);
1589                prune->path[prune->nr++] = xstrdup(sb->buf);
1590        }
1591}
1592
1593static void read_revisions_from_stdin(struct rev_info *revs,
1594                                      struct cmdline_pathspec *prune)
1595{
1596        struct strbuf sb;
1597        int seen_dashdash = 0;
1598        int save_warning;
1599
1600        save_warning = warn_on_object_refname_ambiguity;
1601        warn_on_object_refname_ambiguity = 0;
1602
1603        strbuf_init(&sb, 1000);
1604        while (strbuf_getwholeline(&sb, stdin, '\n') != EOF) {
1605                int len = sb.len;
1606                if (len && sb.buf[len - 1] == '\n')
1607                        sb.buf[--len] = '\0';
1608                if (!len)
1609                        break;
1610                if (sb.buf[0] == '-') {
1611                        if (len == 2 && sb.buf[1] == '-') {
1612                                seen_dashdash = 1;
1613                                break;
1614                        }
1615                        die("options not supported in --stdin mode");
1616                }
1617                if (handle_revision_arg(sb.buf, revs, 0,
1618                                        REVARG_CANNOT_BE_FILENAME))
1619                        die("bad revision '%s'", sb.buf);
1620        }
1621        if (seen_dashdash)
1622                read_pathspec_from_stdin(revs, &sb, prune);
1623
1624        strbuf_release(&sb);
1625        warn_on_object_refname_ambiguity = save_warning;
1626}
1627
1628static void add_grep(struct rev_info *revs, const char *ptn, enum grep_pat_token what)
1629{
1630        append_grep_pattern(&revs->grep_filter, ptn, "command line", 0, what);
1631}
1632
1633static void add_header_grep(struct rev_info *revs, enum grep_header_field field, const char *pattern)
1634{
1635        append_header_grep_pattern(&revs->grep_filter, field, pattern);
1636}
1637
1638static void add_message_grep(struct rev_info *revs, const char *pattern)
1639{
1640        add_grep(revs, pattern, GREP_PATTERN_BODY);
1641}
1642
1643static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv,
1644                               int *unkc, const char **unkv)
1645{
1646        const char *arg = argv[0];
1647        const char *optarg;
1648        int argcount;
1649
1650        /* pseudo revision arguments */
1651        if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") ||
1652            !strcmp(arg, "--tags") || !strcmp(arg, "--remotes") ||
1653            !strcmp(arg, "--reflog") || !strcmp(arg, "--not") ||
1654            !strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk") ||
1655            !strcmp(arg, "--bisect") || starts_with(arg, "--glob=") ||
1656            starts_with(arg, "--exclude=") ||
1657            starts_with(arg, "--branches=") || starts_with(arg, "--tags=") ||
1658            starts_with(arg, "--remotes=") || starts_with(arg, "--no-walk="))
1659        {
1660                unkv[(*unkc)++] = arg;
1661                return 1;
1662        }
1663
1664        if ((argcount = parse_long_opt("max-count", argv, &optarg))) {
1665                revs->max_count = atoi(optarg);
1666                revs->no_walk = 0;
1667                return argcount;
1668        } else if ((argcount = parse_long_opt("skip", argv, &optarg))) {
1669                revs->skip_count = atoi(optarg);
1670                return argcount;
1671        } else if ((*arg == '-') && isdigit(arg[1])) {
1672                /* accept -<digit>, like traditional "head" */
1673                if (strtol_i(arg + 1, 10, &revs->max_count) < 0 ||
1674                    revs->max_count < 0)
1675                        die("'%s': not a non-negative integer", arg + 1);
1676                revs->no_walk = 0;
1677        } else if (!strcmp(arg, "-n")) {
1678                if (argc <= 1)
1679                        return error("-n requires an argument");
1680                revs->max_count = atoi(argv[1]);
1681                revs->no_walk = 0;
1682                return 2;
1683        } else if (starts_with(arg, "-n")) {
1684                revs->max_count = atoi(arg + 2);
1685                revs->no_walk = 0;
1686        } else if ((argcount = parse_long_opt("max-age", argv, &optarg))) {
1687                revs->max_age = atoi(optarg);
1688                return argcount;
1689        } else if ((argcount = parse_long_opt("since", argv, &optarg))) {
1690                revs->max_age = approxidate(optarg);
1691                return argcount;
1692        } else if ((argcount = parse_long_opt("after", argv, &optarg))) {
1693                revs->max_age = approxidate(optarg);
1694                return argcount;
1695        } else if ((argcount = parse_long_opt("min-age", argv, &optarg))) {
1696                revs->min_age = atoi(optarg);
1697                return argcount;
1698        } else if ((argcount = parse_long_opt("before", argv, &optarg))) {
1699                revs->min_age = approxidate(optarg);
1700                return argcount;
1701        } else if ((argcount = parse_long_opt("until", argv, &optarg))) {
1702                revs->min_age = approxidate(optarg);
1703                return argcount;
1704        } else if (!strcmp(arg, "--first-parent")) {
1705                revs->first_parent_only = 1;
1706        } else if (!strcmp(arg, "--ancestry-path")) {
1707                revs->ancestry_path = 1;
1708                revs->simplify_history = 0;
1709                revs->limited = 1;
1710        } else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) {
1711                init_reflog_walk(&revs->reflog_info);
1712        } else if (!strcmp(arg, "--default")) {
1713                if (argc <= 1)
1714                        return error("bad --default argument");
1715                revs->def = argv[1];
1716                return 2;
1717        } else if (!strcmp(arg, "--merge")) {
1718                revs->show_merge = 1;
1719        } else if (!strcmp(arg, "--topo-order")) {
1720                revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
1721                revs->topo_order = 1;
1722        } else if (!strcmp(arg, "--simplify-merges")) {
1723                revs->simplify_merges = 1;
1724                revs->topo_order = 1;
1725                revs->rewrite_parents = 1;
1726                revs->simplify_history = 0;
1727                revs->limited = 1;
1728        } else if (!strcmp(arg, "--simplify-by-decoration")) {
1729                revs->simplify_merges = 1;
1730                revs->topo_order = 1;
1731                revs->rewrite_parents = 1;
1732                revs->simplify_history = 0;
1733                revs->simplify_by_decoration = 1;
1734                revs->limited = 1;
1735                revs->prune = 1;
1736                load_ref_decorations(DECORATE_SHORT_REFS);
1737        } else if (!strcmp(arg, "--date-order")) {
1738                revs->sort_order = REV_SORT_BY_COMMIT_DATE;
1739                revs->topo_order = 1;
1740        } else if (!strcmp(arg, "--author-date-order")) {
1741                revs->sort_order = REV_SORT_BY_AUTHOR_DATE;
1742                revs->topo_order = 1;
1743        } else if (starts_with(arg, "--early-output")) {
1744                int count = 100;
1745                switch (arg[14]) {
1746                case '=':
1747                        count = atoi(arg+15);
1748                        /* Fallthrough */
1749                case 0:
1750                        revs->topo_order = 1;
1751                       revs->early_output = count;
1752                }
1753        } else if (!strcmp(arg, "--parents")) {
1754                revs->rewrite_parents = 1;
1755                revs->print_parents = 1;
1756        } else if (!strcmp(arg, "--dense")) {
1757                revs->dense = 1;
1758        } else if (!strcmp(arg, "--sparse")) {
1759                revs->dense = 0;
1760        } else if (!strcmp(arg, "--show-all")) {
1761                revs->show_all = 1;
1762        } else if (!strcmp(arg, "--remove-empty")) {
1763                revs->remove_empty_trees = 1;
1764        } else if (!strcmp(arg, "--merges")) {
1765                revs->min_parents = 2;
1766        } else if (!strcmp(arg, "--no-merges")) {
1767                revs->max_parents = 1;
1768        } else if (starts_with(arg, "--min-parents=")) {
1769                revs->min_parents = atoi(arg+14);
1770        } else if (starts_with(arg, "--no-min-parents")) {
1771                revs->min_parents = 0;
1772        } else if (starts_with(arg, "--max-parents=")) {
1773                revs->max_parents = atoi(arg+14);
1774        } else if (starts_with(arg, "--no-max-parents")) {
1775                revs->max_parents = -1;
1776        } else if (!strcmp(arg, "--boundary")) {
1777                revs->boundary = 1;
1778        } else if (!strcmp(arg, "--left-right")) {
1779                revs->left_right = 1;
1780        } else if (!strcmp(arg, "--left-only")) {
1781                if (revs->right_only)
1782                        die("--left-only is incompatible with --right-only"
1783                            " or --cherry");
1784                revs->left_only = 1;
1785        } else if (!strcmp(arg, "--right-only")) {
1786                if (revs->left_only)
1787                        die("--right-only is incompatible with --left-only");
1788                revs->right_only = 1;
1789        } else if (!strcmp(arg, "--cherry")) {
1790                if (revs->left_only)
1791                        die("--cherry is incompatible with --left-only");
1792                revs->cherry_mark = 1;
1793                revs->right_only = 1;
1794                revs->max_parents = 1;
1795                revs->limited = 1;
1796        } else if (!strcmp(arg, "--count")) {
1797                revs->count = 1;
1798        } else if (!strcmp(arg, "--cherry-mark")) {
1799                if (revs->cherry_pick)
1800                        die("--cherry-mark is incompatible with --cherry-pick");
1801                revs->cherry_mark = 1;
1802                revs->limited = 1; /* needs limit_list() */
1803        } else if (!strcmp(arg, "--cherry-pick")) {
1804                if (revs->cherry_mark)
1805                        die("--cherry-pick is incompatible with --cherry-mark");
1806                revs->cherry_pick = 1;
1807                revs->limited = 1;
1808        } else if (!strcmp(arg, "--objects")) {
1809                revs->tag_objects = 1;
1810                revs->tree_objects = 1;
1811                revs->blob_objects = 1;
1812        } else if (!strcmp(arg, "--objects-edge")) {
1813                revs->tag_objects = 1;
1814                revs->tree_objects = 1;
1815                revs->blob_objects = 1;
1816                revs->edge_hint = 1;
1817        } else if (!strcmp(arg, "--verify-objects")) {
1818                revs->tag_objects = 1;
1819                revs->tree_objects = 1;
1820                revs->blob_objects = 1;
1821                revs->verify_objects = 1;
1822        } else if (!strcmp(arg, "--unpacked")) {
1823                revs->unpacked = 1;
1824        } else if (starts_with(arg, "--unpacked=")) {
1825                die("--unpacked=<packfile> no longer supported.");
1826        } else if (!strcmp(arg, "-r")) {
1827                revs->diff = 1;
1828                DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
1829        } else if (!strcmp(arg, "-t")) {
1830                revs->diff = 1;
1831                DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
1832                DIFF_OPT_SET(&revs->diffopt, TREE_IN_RECURSIVE);
1833        } else if (!strcmp(arg, "-m")) {
1834                revs->ignore_merges = 0;
1835        } else if (!strcmp(arg, "-c")) {
1836                revs->diff = 1;
1837                revs->dense_combined_merges = 0;
1838                revs->combine_merges = 1;
1839        } else if (!strcmp(arg, "--cc")) {
1840                revs->diff = 1;
1841                revs->dense_combined_merges = 1;
1842                revs->combine_merges = 1;
1843        } else if (!strcmp(arg, "-v")) {
1844                revs->verbose_header = 1;
1845        } else if (!strcmp(arg, "--pretty")) {
1846                revs->verbose_header = 1;
1847                revs->pretty_given = 1;
1848                get_commit_format(NULL, revs);
1849        } else if (starts_with(arg, "--pretty=") || starts_with(arg, "--format=")) {
1850                /*
1851                 * Detached form ("--pretty X" as opposed to "--pretty=X")
1852                 * not allowed, since the argument is optional.
1853                 */
1854                revs->verbose_header = 1;
1855                revs->pretty_given = 1;
1856                get_commit_format(arg+9, revs);
1857        } else if (!strcmp(arg, "--show-notes") || !strcmp(arg, "--notes")) {
1858                revs->show_notes = 1;
1859                revs->show_notes_given = 1;
1860                revs->notes_opt.use_default_notes = 1;
1861        } else if (!strcmp(arg, "--show-signature")) {
1862                revs->show_signature = 1;
1863        } else if (!strcmp(arg, "--show-linear-break") ||
1864                   starts_with(arg, "--show-linear-break=")) {
1865                if (starts_with(arg, "--show-linear-break="))
1866                        revs->break_bar = xstrdup(arg + 20);
1867                else
1868                        revs->break_bar = "                    ..........";
1869                revs->track_linear = 1;
1870                revs->track_first_time = 1;
1871        } else if (starts_with(arg, "--show-notes=") ||
1872                   starts_with(arg, "--notes=")) {
1873                struct strbuf buf = STRBUF_INIT;
1874                revs->show_notes = 1;
1875                revs->show_notes_given = 1;
1876                if (starts_with(arg, "--show-notes")) {
1877                        if (revs->notes_opt.use_default_notes < 0)
1878                                revs->notes_opt.use_default_notes = 1;
1879                        strbuf_addstr(&buf, arg+13);
1880                }
1881                else
1882                        strbuf_addstr(&buf, arg+8);
1883                expand_notes_ref(&buf);
1884                string_list_append(&revs->notes_opt.extra_notes_refs,
1885                                   strbuf_detach(&buf, NULL));
1886        } else if (!strcmp(arg, "--no-notes")) {
1887                revs->show_notes = 0;
1888                revs->show_notes_given = 1;
1889                revs->notes_opt.use_default_notes = -1;
1890                /* we have been strdup'ing ourselves, so trick
1891                 * string_list into free()ing strings */
1892                revs->notes_opt.extra_notes_refs.strdup_strings = 1;
1893                string_list_clear(&revs->notes_opt.extra_notes_refs, 0);
1894                revs->notes_opt.extra_notes_refs.strdup_strings = 0;
1895        } else if (!strcmp(arg, "--standard-notes")) {
1896                revs->show_notes_given = 1;
1897                revs->notes_opt.use_default_notes = 1;
1898        } else if (!strcmp(arg, "--no-standard-notes")) {
1899                revs->notes_opt.use_default_notes = 0;
1900        } else if (!strcmp(arg, "--oneline")) {
1901                revs->verbose_header = 1;
1902                get_commit_format("oneline", revs);
1903                revs->pretty_given = 1;
1904                revs->abbrev_commit = 1;
1905        } else if (!strcmp(arg, "--graph")) {
1906                revs->topo_order = 1;
1907                revs->rewrite_parents = 1;
1908                revs->graph = graph_init(revs);
1909        } else if (!strcmp(arg, "--root")) {
1910                revs->show_root_diff = 1;
1911        } else if (!strcmp(arg, "--no-commit-id")) {
1912                revs->no_commit_id = 1;
1913        } else if (!strcmp(arg, "--always")) {
1914                revs->always_show_header = 1;
1915        } else if (!strcmp(arg, "--no-abbrev")) {
1916                revs->abbrev = 0;
1917        } else if (!strcmp(arg, "--abbrev")) {
1918                revs->abbrev = DEFAULT_ABBREV;
1919        } else if (starts_with(arg, "--abbrev=")) {
1920                revs->abbrev = strtoul(arg + 9, NULL, 10);
1921                if (revs->abbrev < MINIMUM_ABBREV)
1922                        revs->abbrev = MINIMUM_ABBREV;
1923                else if (revs->abbrev > 40)
1924                        revs->abbrev = 40;
1925        } else if (!strcmp(arg, "--abbrev-commit")) {
1926                revs->abbrev_commit = 1;
1927                revs->abbrev_commit_given = 1;
1928        } else if (!strcmp(arg, "--no-abbrev-commit")) {
1929                revs->abbrev_commit = 0;
1930        } else if (!strcmp(arg, "--full-diff")) {
1931                revs->diff = 1;
1932                revs->full_diff = 1;
1933        } else if (!strcmp(arg, "--full-history")) {
1934                revs->simplify_history = 0;
1935        } else if (!strcmp(arg, "--relative-date")) {
1936                revs->date_mode = DATE_RELATIVE;
1937                revs->date_mode_explicit = 1;
1938        } else if ((argcount = parse_long_opt("date", argv, &optarg))) {
1939                revs->date_mode = parse_date_format(optarg);
1940                revs->date_mode_explicit = 1;
1941                return argcount;
1942        } else if (!strcmp(arg, "--log-size")) {
1943                revs->show_log_size = 1;
1944        }
1945        /*
1946         * Grepping the commit log
1947         */
1948        else if ((argcount = parse_long_opt("author", argv, &optarg))) {
1949                add_header_grep(revs, GREP_HEADER_AUTHOR, optarg);
1950                return argcount;
1951        } else if ((argcount = parse_long_opt("committer", argv, &optarg))) {
1952                add_header_grep(revs, GREP_HEADER_COMMITTER, optarg);
1953                return argcount;
1954        } else if ((argcount = parse_long_opt("grep-reflog", argv, &optarg))) {
1955                add_header_grep(revs, GREP_HEADER_REFLOG, optarg);
1956                return argcount;
1957        } else if ((argcount = parse_long_opt("grep", argv, &optarg))) {
1958                add_message_grep(revs, optarg);
1959                return argcount;
1960        } else if (!strcmp(arg, "--grep-debug")) {
1961                revs->grep_filter.debug = 1;
1962        } else if (!strcmp(arg, "--basic-regexp")) {
1963                grep_set_pattern_type_option(GREP_PATTERN_TYPE_BRE, &revs->grep_filter);
1964        } else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) {
1965                grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, &revs->grep_filter);
1966        } else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) {
1967                revs->grep_filter.regflags |= REG_ICASE;
1968                DIFF_OPT_SET(&revs->diffopt, PICKAXE_IGNORE_CASE);
1969        } else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) {
1970                grep_set_pattern_type_option(GREP_PATTERN_TYPE_FIXED, &revs->grep_filter);
1971        } else if (!strcmp(arg, "--perl-regexp")) {
1972                grep_set_pattern_type_option(GREP_PATTERN_TYPE_PCRE, &revs->grep_filter);
1973        } else if (!strcmp(arg, "--all-match")) {
1974                revs->grep_filter.all_match = 1;
1975        } else if ((argcount = parse_long_opt("encoding", argv, &optarg))) {
1976                if (strcmp(optarg, "none"))
1977                        git_log_output_encoding = xstrdup(optarg);
1978                else
1979                        git_log_output_encoding = "";
1980                return argcount;
1981        } else if (!strcmp(arg, "--reverse")) {
1982                revs->reverse ^= 1;
1983        } else if (!strcmp(arg, "--children")) {
1984                revs->children.name = "children";
1985                revs->limited = 1;
1986        } else if (!strcmp(arg, "--ignore-missing")) {
1987                revs->ignore_missing = 1;
1988        } else {
1989                int opts = diff_opt_parse(&revs->diffopt, argv, argc);
1990                if (!opts)
1991                        unkv[(*unkc)++] = arg;
1992                return opts;
1993        }
1994        if (revs->graph && revs->track_linear)
1995                die("--show-linear-break and --graph are incompatible");
1996
1997        return 1;
1998}
1999
2000void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx,
2001                        const struct option *options,
2002                        const char * const usagestr[])
2003{
2004        int n = handle_revision_opt(revs, ctx->argc, ctx->argv,
2005                                    &ctx->cpidx, ctx->out);
2006        if (n <= 0) {
2007                error("unknown option `%s'", ctx->argv[0]);
2008                usage_with_options(usagestr, options);
2009        }
2010        ctx->argv += n;
2011        ctx->argc -= n;
2012}
2013
2014static int for_each_bad_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2015{
2016        return for_each_ref_in_submodule(submodule, "refs/bisect/bad", fn, cb_data);
2017}
2018
2019static int for_each_good_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2020{
2021        return for_each_ref_in_submodule(submodule, "refs/bisect/good", fn, cb_data);
2022}
2023
2024static int handle_revision_pseudo_opt(const char *submodule,
2025                                struct rev_info *revs,
2026                                int argc, const char **argv, int *flags)
2027{
2028        const char *arg = argv[0];
2029        const char *optarg;
2030        int argcount;
2031
2032        /*
2033         * NOTE!
2034         *
2035         * Commands like "git shortlog" will not accept the options below
2036         * unless parse_revision_opt queues them (as opposed to erroring
2037         * out).
2038         *
2039         * When implementing your new pseudo-option, remember to
2040         * register it in the list at the top of handle_revision_opt.
2041         */
2042        if (!strcmp(arg, "--all")) {
2043                handle_refs(submodule, revs, *flags, for_each_ref_submodule);
2044                handle_refs(submodule, revs, *flags, head_ref_submodule);
2045                clear_ref_exclusion(&revs->ref_excludes);
2046        } else if (!strcmp(arg, "--branches")) {
2047                handle_refs(submodule, revs, *flags, for_each_branch_ref_submodule);
2048                clear_ref_exclusion(&revs->ref_excludes);
2049        } else if (!strcmp(arg, "--bisect")) {
2050                handle_refs(submodule, revs, *flags, for_each_bad_bisect_ref);
2051                handle_refs(submodule, revs, *flags ^ (UNINTERESTING | BOTTOM), for_each_good_bisect_ref);
2052                revs->bisect = 1;
2053        } else if (!strcmp(arg, "--tags")) {
2054                handle_refs(submodule, revs, *flags, for_each_tag_ref_submodule);
2055                clear_ref_exclusion(&revs->ref_excludes);
2056        } else if (!strcmp(arg, "--remotes")) {
2057                handle_refs(submodule, revs, *flags, for_each_remote_ref_submodule);
2058                clear_ref_exclusion(&revs->ref_excludes);
2059        } else if ((argcount = parse_long_opt("glob", argv, &optarg))) {
2060                struct all_refs_cb cb;
2061                init_all_refs_cb(&cb, revs, *flags);
2062                for_each_glob_ref(handle_one_ref, optarg, &cb);
2063                clear_ref_exclusion(&revs->ref_excludes);
2064                return argcount;
2065        } else if ((argcount = parse_long_opt("exclude", argv, &optarg))) {
2066                add_ref_exclusion(&revs->ref_excludes, optarg);
2067                return argcount;
2068        } else if (starts_with(arg, "--branches=")) {
2069                struct all_refs_cb cb;
2070                init_all_refs_cb(&cb, revs, *flags);
2071                for_each_glob_ref_in(handle_one_ref, arg + 11, "refs/heads/", &cb);
2072                clear_ref_exclusion(&revs->ref_excludes);
2073        } else if (starts_with(arg, "--tags=")) {
2074                struct all_refs_cb cb;
2075                init_all_refs_cb(&cb, revs, *flags);
2076                for_each_glob_ref_in(handle_one_ref, arg + 7, "refs/tags/", &cb);
2077                clear_ref_exclusion(&revs->ref_excludes);
2078        } else if (starts_with(arg, "--remotes=")) {
2079                struct all_refs_cb cb;
2080                init_all_refs_cb(&cb, revs, *flags);
2081                for_each_glob_ref_in(handle_one_ref, arg + 10, "refs/remotes/", &cb);
2082                clear_ref_exclusion(&revs->ref_excludes);
2083        } else if (!strcmp(arg, "--reflog")) {
2084                add_reflogs_to_pending(revs, *flags);
2085        } else if (!strcmp(arg, "--not")) {
2086                *flags ^= UNINTERESTING | BOTTOM;
2087        } else if (!strcmp(arg, "--no-walk")) {
2088                revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
2089        } else if (starts_with(arg, "--no-walk=")) {
2090                /*
2091                 * Detached form ("--no-walk X" as opposed to "--no-walk=X")
2092                 * not allowed, since the argument is optional.
2093                 */
2094                if (!strcmp(arg + 10, "sorted"))
2095                        revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
2096                else if (!strcmp(arg + 10, "unsorted"))
2097                        revs->no_walk = REVISION_WALK_NO_WALK_UNSORTED;
2098                else
2099                        return error("invalid argument to --no-walk");
2100        } else if (!strcmp(arg, "--do-walk")) {
2101                revs->no_walk = 0;
2102        } else {
2103                return 0;
2104        }
2105
2106        return 1;
2107}
2108
2109/*
2110 * Parse revision information, filling in the "rev_info" structure,
2111 * and removing the used arguments from the argument list.
2112 *
2113 * Returns the number of arguments left that weren't recognized
2114 * (which are also moved to the head of the argument list)
2115 */
2116int setup_revisions(int argc, const char **argv, struct rev_info *revs, struct setup_revision_opt *opt)
2117{
2118        int i, flags, left, seen_dashdash, read_from_stdin, got_rev_arg = 0, revarg_opt;
2119        struct cmdline_pathspec prune_data;
2120        const char *submodule = NULL;
2121
2122        memset(&prune_data, 0, sizeof(prune_data));
2123        if (opt)
2124                submodule = opt->submodule;
2125
2126        /* First, search for "--" */
2127        if (opt && opt->assume_dashdash) {
2128                seen_dashdash = 1;
2129        } else {
2130                seen_dashdash = 0;
2131                for (i = 1; i < argc; i++) {
2132                        const char *arg = argv[i];
2133                        if (strcmp(arg, "--"))
2134                                continue;
2135                        argv[i] = NULL;
2136                        argc = i;
2137                        if (argv[i + 1])
2138                                append_prune_data(&prune_data, argv + i + 1);
2139                        seen_dashdash = 1;
2140                        break;
2141                }
2142        }
2143
2144        /* Second, deal with arguments and options */
2145        flags = 0;
2146        revarg_opt = opt ? opt->revarg_opt : 0;
2147        if (seen_dashdash)
2148                revarg_opt |= REVARG_CANNOT_BE_FILENAME;
2149        read_from_stdin = 0;
2150        for (left = i = 1; i < argc; i++) {
2151                const char *arg = argv[i];
2152                if (*arg == '-') {
2153                        int opts;
2154
2155                        opts = handle_revision_pseudo_opt(submodule,
2156                                                revs, argc - i, argv + i,
2157                                                &flags);
2158                        if (opts > 0) {
2159                                i += opts - 1;
2160                                continue;
2161                        }
2162
2163                        if (!strcmp(arg, "--stdin")) {
2164                                if (revs->disable_stdin) {
2165                                        argv[left++] = arg;
2166                                        continue;
2167                                }
2168                                if (read_from_stdin++)
2169                                        die("--stdin given twice?");
2170                                read_revisions_from_stdin(revs, &prune_data);
2171                                continue;
2172                        }
2173
2174                        opts = handle_revision_opt(revs, argc - i, argv + i, &left, argv);
2175                        if (opts > 0) {
2176                                i += opts - 1;
2177                                continue;
2178                        }
2179                        if (opts < 0)
2180                                exit(128);
2181                        continue;
2182                }
2183
2184
2185                if (handle_revision_arg(arg, revs, flags, revarg_opt)) {
2186                        int j;
2187                        if (seen_dashdash || *arg == '^')
2188                                die("bad revision '%s'", arg);
2189
2190                        /* If we didn't have a "--":
2191                         * (1) all filenames must exist;
2192                         * (2) all rev-args must not be interpretable
2193                         *     as a valid filename.
2194                         * but the latter we have checked in the main loop.
2195                         */
2196                        for (j = i; j < argc; j++)
2197                                verify_filename(revs->prefix, argv[j], j == i);
2198
2199                        append_prune_data(&prune_data, argv + i);
2200                        break;
2201                }
2202                else
2203                        got_rev_arg = 1;
2204        }
2205
2206        if (prune_data.nr) {
2207                /*
2208                 * If we need to introduce the magic "a lone ':' means no
2209                 * pathspec whatsoever", here is the place to do so.
2210                 *
2211                 * if (prune_data.nr == 1 && !strcmp(prune_data[0], ":")) {
2212                 *      prune_data.nr = 0;
2213                 *      prune_data.alloc = 0;
2214                 *      free(prune_data.path);
2215                 *      prune_data.path = NULL;
2216                 * } else {
2217                 *      terminate prune_data.alloc with NULL and
2218                 *      call init_pathspec() to set revs->prune_data here.
2219                 * }
2220                 */
2221                ALLOC_GROW(prune_data.path, prune_data.nr + 1, prune_data.alloc);
2222                prune_data.path[prune_data.nr++] = NULL;
2223                parse_pathspec(&revs->prune_data, 0, 0,
2224                               revs->prefix, prune_data.path);
2225        }
2226
2227        if (revs->def == NULL)
2228                revs->def = opt ? opt->def : NULL;
2229        if (opt && opt->tweak)
2230                opt->tweak(revs, opt);
2231        if (revs->show_merge)
2232                prepare_show_merge(revs);
2233        if (revs->def && !revs->pending.nr && !got_rev_arg) {
2234                unsigned char sha1[20];
2235                struct object *object;
2236                struct object_context oc;
2237                if (get_sha1_with_context(revs->def, 0, sha1, &oc))
2238                        die("bad default revision '%s'", revs->def);
2239                object = get_reference(revs, revs->def, sha1, 0);
2240                add_pending_object_with_mode(revs, object, revs->def, oc.mode);
2241        }
2242
2243        /* Did the user ask for any diff output? Run the diff! */
2244        if (revs->diffopt.output_format & ~DIFF_FORMAT_NO_OUTPUT)
2245                revs->diff = 1;
2246
2247        /* Pickaxe, diff-filter and rename following need diffs */
2248        if (revs->diffopt.pickaxe ||
2249            revs->diffopt.filter ||
2250            DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
2251                revs->diff = 1;
2252
2253        if (revs->topo_order)
2254                revs->limited = 1;
2255
2256        if (revs->prune_data.nr) {
2257                copy_pathspec(&revs->pruning.pathspec, &revs->prune_data);
2258                /* Can't prune commits with rename following: the paths change.. */
2259                if (!DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
2260                        revs->prune = 1;
2261                if (!revs->full_diff)
2262                        copy_pathspec(&revs->diffopt.pathspec,
2263                                      &revs->prune_data);
2264        }
2265        if (revs->combine_merges)
2266                revs->ignore_merges = 0;
2267        revs->diffopt.abbrev = revs->abbrev;
2268
2269        if (revs->line_level_traverse) {
2270                revs->limited = 1;
2271                revs->topo_order = 1;
2272        }
2273
2274        diff_setup_done(&revs->diffopt);
2275
2276        grep_commit_pattern_type(GREP_PATTERN_TYPE_UNSPECIFIED,
2277                                 &revs->grep_filter);
2278        compile_grep_patterns(&revs->grep_filter);
2279
2280        if (revs->reverse && revs->reflog_info)
2281                die("cannot combine --reverse with --walk-reflogs");
2282        if (revs->rewrite_parents && revs->children.name)
2283                die("cannot combine --parents and --children");
2284
2285        /*
2286         * Limitations on the graph functionality
2287         */
2288        if (revs->reverse && revs->graph)
2289                die("cannot combine --reverse with --graph");
2290
2291        if (revs->reflog_info && revs->graph)
2292                die("cannot combine --walk-reflogs with --graph");
2293        if (!revs->reflog_info && revs->grep_filter.use_reflog_filter)
2294                die("cannot use --grep-reflog without --walk-reflogs");
2295
2296        return left;
2297}
2298
2299static void add_child(struct rev_info *revs, struct commit *parent, struct commit *child)
2300{
2301        struct commit_list *l = xcalloc(1, sizeof(*l));
2302
2303        l->item = child;
2304        l->next = add_decoration(&revs->children, &parent->object, l);
2305}
2306
2307static int remove_duplicate_parents(struct rev_info *revs, struct commit *commit)
2308{
2309        struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
2310        struct commit_list **pp, *p;
2311        int surviving_parents;
2312
2313        /* Examine existing parents while marking ones we have seen... */
2314        pp = &commit->parents;
2315        surviving_parents = 0;
2316        while ((p = *pp) != NULL) {
2317                struct commit *parent = p->item;
2318                if (parent->object.flags & TMP_MARK) {
2319                        *pp = p->next;
2320                        if (ts)
2321                                compact_treesame(revs, commit, surviving_parents);
2322                        continue;
2323                }
2324                parent->object.flags |= TMP_MARK;
2325                surviving_parents++;
2326                pp = &p->next;
2327        }
2328        /* clear the temporary mark */
2329        for (p = commit->parents; p; p = p->next) {
2330                p->item->object.flags &= ~TMP_MARK;
2331        }
2332        /* no update_treesame() - removing duplicates can't affect TREESAME */
2333        return surviving_parents;
2334}
2335
2336struct merge_simplify_state {
2337        struct commit *simplified;
2338};
2339
2340static struct merge_simplify_state *locate_simplify_state(struct rev_info *revs, struct commit *commit)
2341{
2342        struct merge_simplify_state *st;
2343
2344        st = lookup_decoration(&revs->merge_simplification, &commit->object);
2345        if (!st) {
2346                st = xcalloc(1, sizeof(*st));
2347                add_decoration(&revs->merge_simplification, &commit->object, st);
2348        }
2349        return st;
2350}
2351
2352static int mark_redundant_parents(struct rev_info *revs, struct commit *commit)
2353{
2354        struct commit_list *h = reduce_heads(commit->parents);
2355        int i = 0, marked = 0;
2356        struct commit_list *po, *pn;
2357
2358        /* Want these for sanity-checking only */
2359        int orig_cnt = commit_list_count(commit->parents);
2360        int cnt = commit_list_count(h);
2361
2362        /*
2363         * Not ready to remove items yet, just mark them for now, based
2364         * on the output of reduce_heads(). reduce_heads outputs the reduced
2365         * set in its original order, so this isn't too hard.
2366         */
2367        po = commit->parents;
2368        pn = h;
2369        while (po) {
2370                if (pn && po->item == pn->item) {
2371                        pn = pn->next;
2372                        i++;
2373                } else {
2374                        po->item->object.flags |= TMP_MARK;
2375                        marked++;
2376                }
2377                po=po->next;
2378        }
2379
2380        if (i != cnt || cnt+marked != orig_cnt)
2381                die("mark_redundant_parents %d %d %d %d", orig_cnt, cnt, i, marked);
2382
2383        free_commit_list(h);
2384
2385        return marked;
2386}
2387
2388static int mark_treesame_root_parents(struct rev_info *revs, struct commit *commit)
2389{
2390        struct commit_list *p;
2391        int marked = 0;
2392
2393        for (p = commit->parents; p; p = p->next) {
2394                struct commit *parent = p->item;
2395                if (!parent->parents && (parent->object.flags & TREESAME)) {
2396                        parent->object.flags |= TMP_MARK;
2397                        marked++;
2398                }
2399        }
2400
2401        return marked;
2402}
2403
2404/*
2405 * Awkward naming - this means one parent we are TREESAME to.
2406 * cf mark_treesame_root_parents: root parents that are TREESAME (to an
2407 * empty tree). Better name suggestions?
2408 */
2409static int leave_one_treesame_to_parent(struct rev_info *revs, struct commit *commit)
2410{
2411        struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
2412        struct commit *unmarked = NULL, *marked = NULL;
2413        struct commit_list *p;
2414        unsigned n;
2415
2416        for (p = commit->parents, n = 0; p; p = p->next, n++) {
2417                if (ts->treesame[n]) {
2418                        if (p->item->object.flags & TMP_MARK) {
2419                                if (!marked)
2420                                        marked = p->item;
2421                        } else {
2422                                if (!unmarked) {
2423                                        unmarked = p->item;
2424                                        break;
2425                                }
2426                        }
2427                }
2428        }
2429
2430        /*
2431         * If we are TREESAME to a marked-for-deletion parent, but not to any
2432         * unmarked parents, unmark the first TREESAME parent. This is the
2433         * parent that the default simplify_history==1 scan would have followed,
2434         * and it doesn't make sense to omit that path when asking for a
2435         * simplified full history. Retaining it improves the chances of
2436         * understanding odd missed merges that took an old version of a file.
2437         *
2438         * Example:
2439         *
2440         *   I--------*X       A modified the file, but mainline merge X used
2441         *    \       /        "-s ours", so took the version from I. X is
2442         *     `-*A--'         TREESAME to I and !TREESAME to A.
2443         *
2444         * Default log from X would produce "I". Without this check,
2445         * --full-history --simplify-merges would produce "I-A-X", showing
2446         * the merge commit X and that it changed A, but not making clear that
2447         * it had just taken the I version. With this check, the topology above
2448         * is retained.
2449         *
2450         * Note that it is possible that the simplification chooses a different
2451         * TREESAME parent from the default, in which case this test doesn't
2452         * activate, and we _do_ drop the default parent. Example:
2453         *
2454         *   I------X         A modified the file, but it was reverted in B,
2455         *    \    /          meaning mainline merge X is TREESAME to both
2456         *    *A-*B           parents.
2457         *
2458         * Default log would produce "I" by following the first parent;
2459         * --full-history --simplify-merges will produce "I-A-B". But this is a
2460         * reasonable result - it presents a logical full history leading from
2461         * I to X, and X is not an important merge.
2462         */
2463        if (!unmarked && marked) {
2464                marked->object.flags &= ~TMP_MARK;
2465                return 1;
2466        }
2467
2468        return 0;
2469}
2470
2471static int remove_marked_parents(struct rev_info *revs, struct commit *commit)
2472{
2473        struct commit_list **pp, *p;
2474        int nth_parent, removed = 0;
2475
2476        pp = &commit->parents;
2477        nth_parent = 0;
2478        while ((p = *pp) != NULL) {
2479                struct commit *parent = p->item;
2480                if (parent->object.flags & TMP_MARK) {
2481                        parent->object.flags &= ~TMP_MARK;
2482                        *pp = p->next;
2483                        free(p);
2484                        removed++;
2485                        compact_treesame(revs, commit, nth_parent);
2486                        continue;
2487                }
2488                pp = &p->next;
2489                nth_parent++;
2490        }
2491
2492        /* Removing parents can only increase TREESAMEness */
2493        if (removed && !(commit->object.flags & TREESAME))
2494                update_treesame(revs, commit);
2495
2496        return nth_parent;
2497}
2498
2499static struct commit_list **simplify_one(struct rev_info *revs, struct commit *commit, struct commit_list **tail)
2500{
2501        struct commit_list *p;
2502        struct commit *parent;
2503        struct merge_simplify_state *st, *pst;
2504        int cnt;
2505
2506        st = locate_simplify_state(revs, commit);
2507
2508        /*
2509         * Have we handled this one?
2510         */
2511        if (st->simplified)
2512                return tail;
2513
2514        /*
2515         * An UNINTERESTING commit simplifies to itself, so does a
2516         * root commit.  We do not rewrite parents of such commit
2517         * anyway.
2518         */
2519        if ((commit->object.flags & UNINTERESTING) || !commit->parents) {
2520                st->simplified = commit;
2521                return tail;
2522        }
2523
2524        /*
2525         * Do we know what commit all of our parents that matter
2526         * should be rewritten to?  Otherwise we are not ready to
2527         * rewrite this one yet.
2528         */
2529        for (cnt = 0, p = commit->parents; p; p = p->next) {
2530                pst = locate_simplify_state(revs, p->item);
2531                if (!pst->simplified) {
2532                        tail = &commit_list_insert(p->item, tail)->next;
2533                        cnt++;
2534                }
2535                if (revs->first_parent_only)
2536                        break;
2537        }
2538        if (cnt) {
2539                tail = &commit_list_insert(commit, tail)->next;
2540                return tail;
2541        }
2542
2543        /*
2544         * Rewrite our list of parents. Note that this cannot
2545         * affect our TREESAME flags in any way - a commit is
2546         * always TREESAME to its simplification.
2547         */
2548        for (p = commit->parents; p; p = p->next) {
2549                pst = locate_simplify_state(revs, p->item);
2550                p->item = pst->simplified;
2551                if (revs->first_parent_only)
2552                        break;
2553        }
2554
2555        if (revs->first_parent_only)
2556                cnt = 1;
2557        else
2558                cnt = remove_duplicate_parents(revs, commit);
2559
2560        /*
2561         * It is possible that we are a merge and one side branch
2562         * does not have any commit that touches the given paths;
2563         * in such a case, the immediate parent from that branch
2564         * will be rewritten to be the merge base.
2565         *
2566         *      o----X          X: the commit we are looking at;
2567         *     /    /           o: a commit that touches the paths;
2568         * ---o----'
2569         *
2570         * Further, a merge of an independent branch that doesn't
2571         * touch the path will reduce to a treesame root parent:
2572         *
2573         *  ----o----X          X: the commit we are looking at;
2574         *          /           o: a commit that touches the paths;
2575         *         r            r: a root commit not touching the paths
2576         *
2577         * Detect and simplify both cases.
2578         */
2579        if (1 < cnt) {
2580                int marked = mark_redundant_parents(revs, commit);
2581                marked += mark_treesame_root_parents(revs, commit);
2582                if (marked)
2583                        marked -= leave_one_treesame_to_parent(revs, commit);
2584                if (marked)
2585                        cnt = remove_marked_parents(revs, commit);
2586        }
2587
2588        /*
2589         * A commit simplifies to itself if it is a root, if it is
2590         * UNINTERESTING, if it touches the given paths, or if it is a
2591         * merge and its parents don't simplify to one relevant commit
2592         * (the first two cases are already handled at the beginning of
2593         * this function).
2594         *
2595         * Otherwise, it simplifies to what its sole relevant parent
2596         * simplifies to.
2597         */
2598        if (!cnt ||
2599            (commit->object.flags & UNINTERESTING) ||
2600            !(commit->object.flags & TREESAME) ||
2601            (parent = one_relevant_parent(revs, commit->parents)) == NULL)
2602                st->simplified = commit;
2603        else {
2604                pst = locate_simplify_state(revs, parent);
2605                st->simplified = pst->simplified;
2606        }
2607        return tail;
2608}
2609
2610static void simplify_merges(struct rev_info *revs)
2611{
2612        struct commit_list *list, *next;
2613        struct commit_list *yet_to_do, **tail;
2614        struct commit *commit;
2615
2616        if (!revs->prune)
2617                return;
2618
2619        /* feed the list reversed */
2620        yet_to_do = NULL;
2621        for (list = revs->commits; list; list = next) {
2622                commit = list->item;
2623                next = list->next;
2624                /*
2625                 * Do not free(list) here yet; the original list
2626                 * is used later in this function.
2627                 */
2628                commit_list_insert(commit, &yet_to_do);
2629        }
2630        while (yet_to_do) {
2631                list = yet_to_do;
2632                yet_to_do = NULL;
2633                tail = &yet_to_do;
2634                while (list) {
2635                        commit = list->item;
2636                        next = list->next;
2637                        free(list);
2638                        list = next;
2639                        tail = simplify_one(revs, commit, tail);
2640                }
2641        }
2642
2643        /* clean up the result, removing the simplified ones */
2644        list = revs->commits;
2645        revs->commits = NULL;
2646        tail = &revs->commits;
2647        while (list) {
2648                struct merge_simplify_state *st;
2649
2650                commit = list->item;
2651                next = list->next;
2652                free(list);
2653                list = next;
2654                st = locate_simplify_state(revs, commit);
2655                if (st->simplified == commit)
2656                        tail = &commit_list_insert(commit, tail)->next;
2657        }
2658}
2659
2660static void set_children(struct rev_info *revs)
2661{
2662        struct commit_list *l;
2663        for (l = revs->commits; l; l = l->next) {
2664                struct commit *commit = l->item;
2665                struct commit_list *p;
2666
2667                for (p = commit->parents; p; p = p->next)
2668                        add_child(revs, p->item, commit);
2669        }
2670}
2671
2672void reset_revision_walk(void)
2673{
2674        clear_object_flags(SEEN | ADDED | SHOWN);
2675}
2676
2677int prepare_revision_walk(struct rev_info *revs)
2678{
2679        int i;
2680        struct object_array old_pending;
2681        struct commit_list **next = &revs->commits;
2682
2683        memcpy(&old_pending, &revs->pending, sizeof(old_pending));
2684        revs->pending.nr = 0;
2685        revs->pending.alloc = 0;
2686        revs->pending.objects = NULL;
2687        for (i = 0; i < old_pending.nr; i++) {
2688                struct object_array_entry *e = old_pending.objects + i;
2689                struct commit *commit = handle_commit(revs, e);
2690                if (commit) {
2691                        if (!(commit->object.flags & SEEN)) {
2692                                commit->object.flags |= SEEN;
2693                                next = commit_list_append(commit, next);
2694                        }
2695                }
2696        }
2697        if (!revs->leak_pending)
2698                object_array_clear(&old_pending);
2699
2700        /* Signal whether we need per-parent treesame decoration */
2701        if (revs->simplify_merges ||
2702            (revs->limited && limiting_can_increase_treesame(revs)))
2703                revs->treesame.name = "treesame";
2704
2705        if (revs->no_walk != REVISION_WALK_NO_WALK_UNSORTED)
2706                commit_list_sort_by_date(&revs->commits);
2707        if (revs->no_walk)
2708                return 0;
2709        if (revs->limited)
2710                if (limit_list(revs) < 0)
2711                        return -1;
2712        if (revs->topo_order)
2713                sort_in_topological_order(&revs->commits, revs->sort_order);
2714        if (revs->line_level_traverse)
2715                line_log_filter(revs);
2716        if (revs->simplify_merges)
2717                simplify_merges(revs);
2718        if (revs->children.name)
2719                set_children(revs);
2720        return 0;
2721}
2722
2723static enum rewrite_result rewrite_one(struct rev_info *revs, struct commit **pp)
2724{
2725        struct commit_list *cache = NULL;
2726
2727        for (;;) {
2728                struct commit *p = *pp;
2729                if (!revs->limited)
2730                        if (add_parents_to_list(revs, p, &revs->commits, &cache) < 0)
2731                                return rewrite_one_error;
2732                if (p->object.flags & UNINTERESTING)
2733                        return rewrite_one_ok;
2734                if (!(p->object.flags & TREESAME))
2735                        return rewrite_one_ok;
2736                if (!p->parents)
2737                        return rewrite_one_noparents;
2738                if ((p = one_relevant_parent(revs, p->parents)) == NULL)
2739                        return rewrite_one_ok;
2740                *pp = p;
2741        }
2742}
2743
2744int rewrite_parents(struct rev_info *revs, struct commit *commit,
2745        rewrite_parent_fn_t rewrite_parent)
2746{
2747        struct commit_list **pp = &commit->parents;
2748        while (*pp) {
2749                struct commit_list *parent = *pp;
2750                switch (rewrite_parent(revs, &parent->item)) {
2751                case rewrite_one_ok:
2752                        break;
2753                case rewrite_one_noparents:
2754                        *pp = parent->next;
2755                        continue;
2756                case rewrite_one_error:
2757                        return -1;
2758                }
2759                pp = &parent->next;
2760        }
2761        remove_duplicate_parents(revs, commit);
2762        return 0;
2763}
2764
2765static int commit_rewrite_person(struct strbuf *buf, const char *what, struct string_list *mailmap)
2766{
2767        char *person, *endp;
2768        size_t len, namelen, maillen;
2769        const char *name;
2770        const char *mail;
2771        struct ident_split ident;
2772
2773        person = strstr(buf->buf, what);
2774        if (!person)
2775                return 0;
2776
2777        person += strlen(what);
2778        endp = strchr(person, '\n');
2779        if (!endp)
2780                return 0;
2781
2782        len = endp - person;
2783
2784        if (split_ident_line(&ident, person, len))
2785                return 0;
2786
2787        mail = ident.mail_begin;
2788        maillen = ident.mail_end - ident.mail_begin;
2789        name = ident.name_begin;
2790        namelen = ident.name_end - ident.name_begin;
2791
2792        if (map_user(mailmap, &mail, &maillen, &name, &namelen)) {
2793                struct strbuf namemail = STRBUF_INIT;
2794
2795                strbuf_addf(&namemail, "%.*s <%.*s>",
2796                            (int)namelen, name, (int)maillen, mail);
2797
2798                strbuf_splice(buf, ident.name_begin - buf->buf,
2799                              ident.mail_end - ident.name_begin + 1,
2800                              namemail.buf, namemail.len);
2801
2802                strbuf_release(&namemail);
2803
2804                return 1;
2805        }
2806
2807        return 0;
2808}
2809
2810static int commit_match(struct commit *commit, struct rev_info *opt)
2811{
2812        int retval;
2813        const char *encoding;
2814        const char *message;
2815        struct strbuf buf = STRBUF_INIT;
2816
2817        if (!opt->grep_filter.pattern_list && !opt->grep_filter.header_list)
2818                return 1;
2819
2820        /* Prepend "fake" headers as needed */
2821        if (opt->grep_filter.use_reflog_filter) {
2822                strbuf_addstr(&buf, "reflog ");
2823                get_reflog_message(&buf, opt->reflog_info);
2824                strbuf_addch(&buf, '\n');
2825        }
2826
2827        /*
2828         * We grep in the user's output encoding, under the assumption that it
2829         * is the encoding they are most likely to write their grep pattern
2830         * for. In addition, it means we will match the "notes" encoding below,
2831         * so we will not end up with a buffer that has two different encodings
2832         * in it.
2833         */
2834        encoding = get_log_output_encoding();
2835        message = logmsg_reencode(commit, NULL, encoding);
2836
2837        /* Copy the commit to temporary if we are using "fake" headers */
2838        if (buf.len)
2839                strbuf_addstr(&buf, message);
2840
2841        if (opt->grep_filter.header_list && opt->mailmap) {
2842                if (!buf.len)
2843                        strbuf_addstr(&buf, message);
2844
2845                commit_rewrite_person(&buf, "\nauthor ", opt->mailmap);
2846                commit_rewrite_person(&buf, "\ncommitter ", opt->mailmap);
2847        }
2848
2849        /* Append "fake" message parts as needed */
2850        if (opt->show_notes) {
2851                if (!buf.len)
2852                        strbuf_addstr(&buf, message);
2853                format_display_notes(commit->object.sha1, &buf, encoding, 1);
2854        }
2855
2856        /*
2857         * Find either in the original commit message, or in the temporary.
2858         * Note that we cast away the constness of "message" here. It is
2859         * const because it may come from the cached commit buffer. That's OK,
2860         * because we know that it is modifiable heap memory, and that while
2861         * grep_buffer may modify it for speed, it will restore any
2862         * changes before returning.
2863         */
2864        if (buf.len)
2865                retval = grep_buffer(&opt->grep_filter, buf.buf, buf.len);
2866        else
2867                retval = grep_buffer(&opt->grep_filter,
2868                                     (char *)message, strlen(message));
2869        strbuf_release(&buf);
2870        unuse_commit_buffer(commit, message);
2871        return retval;
2872}
2873
2874static inline int want_ancestry(const struct rev_info *revs)
2875{
2876        return (revs->rewrite_parents || revs->children.name);
2877}
2878
2879enum commit_action get_commit_action(struct rev_info *revs, struct commit *commit)
2880{
2881        if (commit->object.flags & SHOWN)
2882                return commit_ignore;
2883        if (revs->unpacked && has_sha1_pack(commit->object.sha1))
2884                return commit_ignore;
2885        if (revs->show_all)
2886                return commit_show;
2887        if (commit->object.flags & UNINTERESTING)
2888                return commit_ignore;
2889        if (revs->min_age != -1 && (commit->date > revs->min_age))
2890                return commit_ignore;
2891        if (revs->min_parents || (revs->max_parents >= 0)) {
2892                int n = commit_list_count(commit->parents);
2893                if ((n < revs->min_parents) ||
2894                    ((revs->max_parents >= 0) && (n > revs->max_parents)))
2895                        return commit_ignore;
2896        }
2897        if (!commit_match(commit, revs))
2898                return commit_ignore;
2899        if (revs->prune && revs->dense) {
2900                /* Commit without changes? */
2901                if (commit->object.flags & TREESAME) {
2902                        int n;
2903                        struct commit_list *p;
2904                        /* drop merges unless we want parenthood */
2905                        if (!want_ancestry(revs))
2906                                return commit_ignore;
2907                        /*
2908                         * If we want ancestry, then need to keep any merges
2909                         * between relevant commits to tie together topology.
2910                         * For consistency with TREESAME and simplification
2911                         * use "relevant" here rather than just INTERESTING,
2912                         * to treat bottom commit(s) as part of the topology.
2913                         */
2914                        for (n = 0, p = commit->parents; p; p = p->next)
2915                                if (relevant_commit(p->item))
2916                                        if (++n >= 2)
2917                                                return commit_show;
2918                        return commit_ignore;
2919                }
2920        }
2921        return commit_show;
2922}
2923
2924enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit)
2925{
2926        enum commit_action action = get_commit_action(revs, commit);
2927
2928        if (action == commit_show &&
2929            !revs->show_all &&
2930            revs->prune && revs->dense && want_ancestry(revs)) {
2931                /*
2932                 * --full-diff on simplified parents is no good: it
2933                 * will show spurious changes from the commits that
2934                 * were elided.  So we save the parents on the side
2935                 * when --full-diff is in effect.
2936                 */
2937                if (revs->full_diff)
2938                        save_parents(revs, commit);
2939                if (rewrite_parents(revs, commit, rewrite_one) < 0)
2940                        return commit_error;
2941        }
2942        return action;
2943}
2944
2945static void track_linear(struct rev_info *revs, struct commit *commit)
2946{
2947        if (revs->track_first_time) {
2948                revs->linear = 1;
2949                revs->track_first_time = 0;
2950        } else {
2951                struct commit_list *p;
2952                for (p = revs->previous_parents; p; p = p->next)
2953                        if (p->item == NULL || /* first commit */
2954                            !hashcmp(p->item->object.sha1, commit->object.sha1))
2955                                break;
2956                revs->linear = p != NULL;
2957        }
2958        if (revs->reverse) {
2959                if (revs->linear)
2960                        commit->object.flags |= TRACK_LINEAR;
2961        }
2962        free_commit_list(revs->previous_parents);
2963        revs->previous_parents = copy_commit_list(commit->parents);
2964}
2965
2966static struct commit *get_revision_1(struct rev_info *revs)
2967{
2968        if (!revs->commits)
2969                return NULL;
2970
2971        do {
2972                struct commit_list *entry = revs->commits;
2973                struct commit *commit = entry->item;
2974
2975                revs->commits = entry->next;
2976                free(entry);
2977
2978                if (revs->reflog_info) {
2979                        save_parents(revs, commit);
2980                        fake_reflog_parent(revs->reflog_info, commit);
2981                        commit->object.flags &= ~(ADDED | SEEN | SHOWN);
2982                }
2983
2984                /*
2985                 * If we haven't done the list limiting, we need to look at
2986                 * the parents here. We also need to do the date-based limiting
2987                 * that we'd otherwise have done in limit_list().
2988                 */
2989                if (!revs->limited) {
2990                        if (revs->max_age != -1 &&
2991                            (commit->date < revs->max_age))
2992                                continue;
2993                        if (add_parents_to_list(revs, commit, &revs->commits, NULL) < 0) {
2994                                if (!revs->ignore_missing_links)
2995                                        die("Failed to traverse parents of commit %s",
2996                                                sha1_to_hex(commit->object.sha1));
2997                        }
2998                }
2999
3000                switch (simplify_commit(revs, commit)) {
3001                case commit_ignore:
3002                        continue;
3003                case commit_error:
3004                        die("Failed to simplify parents of commit %s",
3005                            sha1_to_hex(commit->object.sha1));
3006                default:
3007                        if (revs->track_linear)
3008                                track_linear(revs, commit);
3009                        return commit;
3010                }
3011        } while (revs->commits);
3012        return NULL;
3013}
3014
3015/*
3016 * Return true for entries that have not yet been shown.  (This is an
3017 * object_array_each_func_t.)
3018 */
3019static int entry_unshown(struct object_array_entry *entry, void *cb_data_unused)
3020{
3021        return !(entry->item->flags & SHOWN);
3022}
3023
3024/*
3025 * If array is on the verge of a realloc, garbage-collect any entries
3026 * that have already been shown to try to free up some space.
3027 */
3028static void gc_boundary(struct object_array *array)
3029{
3030        if (array->nr == array->alloc)
3031                object_array_filter(array, entry_unshown, NULL);
3032}
3033
3034static void create_boundary_commit_list(struct rev_info *revs)
3035{
3036        unsigned i;
3037        struct commit *c;
3038        struct object_array *array = &revs->boundary_commits;
3039        struct object_array_entry *objects = array->objects;
3040
3041        /*
3042         * If revs->commits is non-NULL at this point, an error occurred in
3043         * get_revision_1().  Ignore the error and continue printing the
3044         * boundary commits anyway.  (This is what the code has always
3045         * done.)
3046         */
3047        if (revs->commits) {
3048                free_commit_list(revs->commits);
3049                revs->commits = NULL;
3050        }
3051
3052        /*
3053         * Put all of the actual boundary commits from revs->boundary_commits
3054         * into revs->commits
3055         */
3056        for (i = 0; i < array->nr; i++) {
3057                c = (struct commit *)(objects[i].item);
3058                if (!c)
3059                        continue;
3060                if (!(c->object.flags & CHILD_SHOWN))
3061                        continue;
3062                if (c->object.flags & (SHOWN | BOUNDARY))
3063                        continue;
3064                c->object.flags |= BOUNDARY;
3065                commit_list_insert(c, &revs->commits);
3066        }
3067
3068        /*
3069         * If revs->topo_order is set, sort the boundary commits
3070         * in topological order
3071         */
3072        sort_in_topological_order(&revs->commits, revs->sort_order);
3073}
3074
3075static struct commit *get_revision_internal(struct rev_info *revs)
3076{
3077        struct commit *c = NULL;
3078        struct commit_list *l;
3079
3080        if (revs->boundary == 2) {
3081                /*
3082                 * All of the normal commits have already been returned,
3083                 * and we are now returning boundary commits.
3084                 * create_boundary_commit_list() has populated
3085                 * revs->commits with the remaining commits to return.
3086                 */
3087                c = pop_commit(&revs->commits);
3088                if (c)
3089                        c->object.flags |= SHOWN;
3090                return c;
3091        }
3092
3093        /*
3094         * If our max_count counter has reached zero, then we are done. We
3095         * don't simply return NULL because we still might need to show
3096         * boundary commits. But we want to avoid calling get_revision_1, which
3097         * might do a considerable amount of work finding the next commit only
3098         * for us to throw it away.
3099         *
3100         * If it is non-zero, then either we don't have a max_count at all
3101         * (-1), or it is still counting, in which case we decrement.
3102         */
3103        if (revs->max_count) {
3104                c = get_revision_1(revs);
3105                if (c) {
3106                        while (revs->skip_count > 0) {
3107                                revs->skip_count--;
3108                                c = get_revision_1(revs);
3109                                if (!c)
3110                                        break;
3111                        }
3112                }
3113
3114                if (revs->max_count > 0)
3115                        revs->max_count--;
3116        }
3117
3118        if (c)
3119                c->object.flags |= SHOWN;
3120
3121        if (!revs->boundary)
3122                return c;
3123
3124        if (!c) {
3125                /*
3126                 * get_revision_1() runs out the commits, and
3127                 * we are done computing the boundaries.
3128                 * switch to boundary commits output mode.
3129                 */
3130                revs->boundary = 2;
3131
3132                /*
3133                 * Update revs->commits to contain the list of
3134                 * boundary commits.
3135                 */
3136                create_boundary_commit_list(revs);
3137
3138                return get_revision_internal(revs);
3139        }
3140
3141        /*
3142         * boundary commits are the commits that are parents of the
3143         * ones we got from get_revision_1() but they themselves are
3144         * not returned from get_revision_1().  Before returning
3145         * 'c', we need to mark its parents that they could be boundaries.
3146         */
3147
3148        for (l = c->parents; l; l = l->next) {
3149                struct object *p;
3150                p = &(l->item->object);
3151                if (p->flags & (CHILD_SHOWN | SHOWN))
3152                        continue;
3153                p->flags |= CHILD_SHOWN;
3154                gc_boundary(&revs->boundary_commits);
3155                add_object_array(p, NULL, &revs->boundary_commits);
3156        }
3157
3158        return c;
3159}
3160
3161struct commit *get_revision(struct rev_info *revs)
3162{
3163        struct commit *c;
3164        struct commit_list *reversed;
3165
3166        if (revs->reverse) {
3167                reversed = NULL;
3168                while ((c = get_revision_internal(revs)))
3169                        commit_list_insert(c, &reversed);
3170                revs->commits = reversed;
3171                revs->reverse = 0;
3172                revs->reverse_output_stage = 1;
3173        }
3174
3175        if (revs->reverse_output_stage) {
3176                c = pop_commit(&revs->commits);
3177                if (revs->track_linear)
3178                        revs->linear = !!(c && c->object.flags & TRACK_LINEAR);
3179                return c;
3180        }
3181
3182        c = get_revision_internal(revs);
3183        if (c && revs->graph)
3184                graph_update(revs->graph, c);
3185        if (!c) {
3186                free_saved_parents(revs);
3187                if (revs->previous_parents) {
3188                        free_commit_list(revs->previous_parents);
3189                        revs->previous_parents = NULL;
3190                }
3191        }
3192        return c;
3193}
3194
3195char *get_revision_mark(const struct rev_info *revs, const struct commit *commit)
3196{
3197        if (commit->object.flags & BOUNDARY)
3198                return "-";
3199        else if (commit->object.flags & UNINTERESTING)
3200                return "^";
3201        else if (commit->object.flags & PATCHSAME)
3202                return "=";
3203        else if (!revs || revs->left_right) {
3204                if (commit->object.flags & SYMMETRIC_LEFT)
3205                        return "<";
3206                else
3207                        return ">";
3208        } else if (revs->graph)
3209                return "*";
3210        else if (revs->cherry_mark)
3211                return "+";
3212        return "";
3213}
3214
3215void put_revision_mark(const struct rev_info *revs, const struct commit *commit)
3216{
3217        char *mark = get_revision_mark(revs, commit);
3218        if (!strlen(mark))
3219                return;
3220        fputs(mark, stdout);
3221        putchar(' ');
3222}
3223
3224define_commit_slab(saved_parents, struct commit_list *);
3225
3226#define EMPTY_PARENT_LIST ((struct commit_list *)-1)
3227
3228void save_parents(struct rev_info *revs, struct commit *commit)
3229{
3230        struct commit_list **pp;
3231
3232        if (!revs->saved_parents_slab) {
3233                revs->saved_parents_slab = xmalloc(sizeof(struct saved_parents));
3234                init_saved_parents(revs->saved_parents_slab);
3235        }
3236
3237        pp = saved_parents_at(revs->saved_parents_slab, commit);
3238
3239        /*
3240         * When walking with reflogs, we may visit the same commit
3241         * several times: once for each appearance in the reflog.
3242         *
3243         * In this case, save_parents() will be called multiple times.
3244         * We want to keep only the first set of parents.  We need to
3245         * store a sentinel value for an empty (i.e., NULL) parent
3246         * list to distinguish it from a not-yet-saved list, however.
3247         */
3248        if (*pp)
3249                return;
3250        if (commit->parents)
3251                *pp = copy_commit_list(commit->parents);
3252        else
3253                *pp = EMPTY_PARENT_LIST;
3254}
3255
3256struct commit_list *get_saved_parents(struct rev_info *revs, const struct commit *commit)
3257{
3258        struct commit_list *parents;
3259
3260        if (!revs->saved_parents_slab)
3261                return commit->parents;
3262
3263        parents = *saved_parents_at(revs->saved_parents_slab, commit);
3264        if (parents == EMPTY_PARENT_LIST)
3265                return NULL;
3266        return parents;
3267}
3268
3269void free_saved_parents(struct rev_info *revs)
3270{
3271        if (revs->saved_parents_slab)
3272                clear_saved_parents(revs->saved_parents_slab);
3273}