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