36458265a01bf0aa7f7e8c081e49dadb1882c2ce
   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 process_parents(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                        if (list)
 812                                commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
 813                }
 814                return 0;
 815        }
 816
 817        /*
 818         * Ok, the commit wasn't uninteresting. Try to
 819         * simplify the commit history and find the parent
 820         * that has no differences in the path set if one exists.
 821         */
 822        try_to_simplify_commit(revs, commit);
 823
 824        if (revs->no_walk)
 825                return 0;
 826
 827        left_flag = (commit->object.flags & SYMMETRIC_LEFT);
 828
 829        for (parent = commit->parents; parent; parent = parent->next) {
 830                struct commit *p = parent->item;
 831                int gently = revs->ignore_missing_links ||
 832                             revs->exclude_promisor_objects;
 833                if (parse_commit_gently(p, gently) < 0) {
 834                        if (revs->exclude_promisor_objects &&
 835                            is_promisor_object(&p->object.oid)) {
 836                                if (revs->first_parent_only)
 837                                        break;
 838                                continue;
 839                        }
 840                        return -1;
 841                }
 842                if (revs->sources) {
 843                        char **slot = revision_sources_at(revs->sources, p);
 844
 845                        if (!*slot)
 846                                *slot = *revision_sources_at(revs->sources, commit);
 847                }
 848                p->object.flags |= left_flag;
 849                if (!(p->object.flags & SEEN)) {
 850                        p->object.flags |= SEEN;
 851                        if (list)
 852                                commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
 853                }
 854                if (revs->first_parent_only)
 855                        break;
 856        }
 857        return 0;
 858}
 859
 860static void cherry_pick_list(struct commit_list *list, struct rev_info *revs)
 861{
 862        struct commit_list *p;
 863        int left_count = 0, right_count = 0;
 864        int left_first;
 865        struct patch_ids ids;
 866        unsigned cherry_flag;
 867
 868        /* First count the commits on the left and on the right */
 869        for (p = list; p; p = p->next) {
 870                struct commit *commit = p->item;
 871                unsigned flags = commit->object.flags;
 872                if (flags & BOUNDARY)
 873                        ;
 874                else if (flags & SYMMETRIC_LEFT)
 875                        left_count++;
 876                else
 877                        right_count++;
 878        }
 879
 880        if (!left_count || !right_count)
 881                return;
 882
 883        left_first = left_count < right_count;
 884        init_patch_ids(&ids);
 885        ids.diffopts.pathspec = revs->diffopt.pathspec;
 886
 887        /* Compute patch-ids for one side */
 888        for (p = list; p; p = p->next) {
 889                struct commit *commit = p->item;
 890                unsigned flags = commit->object.flags;
 891
 892                if (flags & BOUNDARY)
 893                        continue;
 894                /*
 895                 * If we have fewer left, left_first is set and we omit
 896                 * commits on the right branch in this loop.  If we have
 897                 * fewer right, we skip the left ones.
 898                 */
 899                if (left_first != !!(flags & SYMMETRIC_LEFT))
 900                        continue;
 901                add_commit_patch_id(commit, &ids);
 902        }
 903
 904        /* either cherry_mark or cherry_pick are true */
 905        cherry_flag = revs->cherry_mark ? PATCHSAME : SHOWN;
 906
 907        /* Check the other side */
 908        for (p = list; p; p = p->next) {
 909                struct commit *commit = p->item;
 910                struct patch_id *id;
 911                unsigned flags = commit->object.flags;
 912
 913                if (flags & BOUNDARY)
 914                        continue;
 915                /*
 916                 * If we have fewer left, left_first is set and we omit
 917                 * commits on the left branch in this loop.
 918                 */
 919                if (left_first == !!(flags & SYMMETRIC_LEFT))
 920                        continue;
 921
 922                /*
 923                 * Have we seen the same patch id?
 924                 */
 925                id = has_commit_patch_id(commit, &ids);
 926                if (!id)
 927                        continue;
 928
 929                commit->object.flags |= cherry_flag;
 930                id->commit->object.flags |= cherry_flag;
 931        }
 932
 933        free_patch_ids(&ids);
 934}
 935
 936/* How many extra uninteresting commits we want to see.. */
 937#define SLOP 5
 938
 939static int still_interesting(struct commit_list *src, timestamp_t date, int slop,
 940                             struct commit **interesting_cache)
 941{
 942        /*
 943         * No source list at all? We're definitely done..
 944         */
 945        if (!src)
 946                return 0;
 947
 948        /*
 949         * Does the destination list contain entries with a date
 950         * before the source list? Definitely _not_ done.
 951         */
 952        if (date <= src->item->date)
 953                return SLOP;
 954
 955        /*
 956         * Does the source list still have interesting commits in
 957         * it? Definitely not done..
 958         */
 959        if (!everybody_uninteresting(src, interesting_cache))
 960                return SLOP;
 961
 962        /* Ok, we're closing in.. */
 963        return slop-1;
 964}
 965
 966/*
 967 * "rev-list --ancestry-path A..B" computes commits that are ancestors
 968 * of B but not ancestors of A but further limits the result to those
 969 * that are descendants of A.  This takes the list of bottom commits and
 970 * the result of "A..B" without --ancestry-path, and limits the latter
 971 * further to the ones that can reach one of the commits in "bottom".
 972 */
 973static void limit_to_ancestry(struct commit_list *bottom, struct commit_list *list)
 974{
 975        struct commit_list *p;
 976        struct commit_list *rlist = NULL;
 977        int made_progress;
 978
 979        /*
 980         * Reverse the list so that it will be likely that we would
 981         * process parents before children.
 982         */
 983        for (p = list; p; p = p->next)
 984                commit_list_insert(p->item, &rlist);
 985
 986        for (p = bottom; p; p = p->next)
 987                p->item->object.flags |= TMP_MARK;
 988
 989        /*
 990         * Mark the ones that can reach bottom commits in "list",
 991         * in a bottom-up fashion.
 992         */
 993        do {
 994                made_progress = 0;
 995                for (p = rlist; p; p = p->next) {
 996                        struct commit *c = p->item;
 997                        struct commit_list *parents;
 998                        if (c->object.flags & (TMP_MARK | UNINTERESTING))
 999                                continue;
1000                        for (parents = c->parents;
1001                             parents;
1002                             parents = parents->next) {
1003                                if (!(parents->item->object.flags & TMP_MARK))
1004                                        continue;
1005                                c->object.flags |= TMP_MARK;
1006                                made_progress = 1;
1007                                break;
1008                        }
1009                }
1010        } while (made_progress);
1011
1012        /*
1013         * NEEDSWORK: decide if we want to remove parents that are
1014         * not marked with TMP_MARK from commit->parents for commits
1015         * in the resulting list.  We may not want to do that, though.
1016         */
1017
1018        /*
1019         * The ones that are not marked with TMP_MARK are uninteresting
1020         */
1021        for (p = list; p; p = p->next) {
1022                struct commit *c = p->item;
1023                if (c->object.flags & TMP_MARK)
1024                        continue;
1025                c->object.flags |= UNINTERESTING;
1026        }
1027
1028        /* We are done with the TMP_MARK */
1029        for (p = list; p; p = p->next)
1030                p->item->object.flags &= ~TMP_MARK;
1031        for (p = bottom; p; p = p->next)
1032                p->item->object.flags &= ~TMP_MARK;
1033        free_commit_list(rlist);
1034}
1035
1036/*
1037 * Before walking the history, keep the set of "negative" refs the
1038 * caller has asked to exclude.
1039 *
1040 * This is used to compute "rev-list --ancestry-path A..B", as we need
1041 * to filter the result of "A..B" further to the ones that can actually
1042 * reach A.
1043 */
1044static struct commit_list *collect_bottom_commits(struct commit_list *list)
1045{
1046        struct commit_list *elem, *bottom = NULL;
1047        for (elem = list; elem; elem = elem->next)
1048                if (elem->item->object.flags & BOTTOM)
1049                        commit_list_insert(elem->item, &bottom);
1050        return bottom;
1051}
1052
1053/* Assumes either left_only or right_only is set */
1054static void limit_left_right(struct commit_list *list, struct rev_info *revs)
1055{
1056        struct commit_list *p;
1057
1058        for (p = list; p; p = p->next) {
1059                struct commit *commit = p->item;
1060
1061                if (revs->right_only) {
1062                        if (commit->object.flags & SYMMETRIC_LEFT)
1063                                commit->object.flags |= SHOWN;
1064                } else  /* revs->left_only is set */
1065                        if (!(commit->object.flags & SYMMETRIC_LEFT))
1066                                commit->object.flags |= SHOWN;
1067        }
1068}
1069
1070static int limit_list(struct rev_info *revs)
1071{
1072        int slop = SLOP;
1073        timestamp_t date = TIME_MAX;
1074        struct commit_list *list = revs->commits;
1075        struct commit_list *newlist = NULL;
1076        struct commit_list **p = &newlist;
1077        struct commit_list *bottom = NULL;
1078        struct commit *interesting_cache = NULL;
1079
1080        if (revs->ancestry_path) {
1081                bottom = collect_bottom_commits(list);
1082                if (!bottom)
1083                        die("--ancestry-path given but there are no bottom commits");
1084        }
1085
1086        while (list) {
1087                struct commit *commit = pop_commit(&list);
1088                struct object *obj = &commit->object;
1089                show_early_output_fn_t show;
1090
1091                if (commit == interesting_cache)
1092                        interesting_cache = NULL;
1093
1094                if (revs->max_age != -1 && (commit->date < revs->max_age))
1095                        obj->flags |= UNINTERESTING;
1096                if (process_parents(revs, commit, &list, NULL) < 0)
1097                        return -1;
1098                if (obj->flags & UNINTERESTING) {
1099                        mark_parents_uninteresting(commit);
1100                        slop = still_interesting(list, date, slop, &interesting_cache);
1101                        if (slop)
1102                                continue;
1103                        break;
1104                }
1105                if (revs->min_age != -1 && (commit->date > revs->min_age))
1106                        continue;
1107                date = commit->date;
1108                p = &commit_list_insert(commit, p)->next;
1109
1110                show = show_early_output;
1111                if (!show)
1112                        continue;
1113
1114                show(revs, newlist);
1115                show_early_output = NULL;
1116        }
1117        if (revs->cherry_pick || revs->cherry_mark)
1118                cherry_pick_list(newlist, revs);
1119
1120        if (revs->left_only || revs->right_only)
1121                limit_left_right(newlist, revs);
1122
1123        if (bottom) {
1124                limit_to_ancestry(bottom, newlist);
1125                free_commit_list(bottom);
1126        }
1127
1128        /*
1129         * Check if any commits have become TREESAME by some of their parents
1130         * becoming UNINTERESTING.
1131         */
1132        if (limiting_can_increase_treesame(revs))
1133                for (list = newlist; list; list = list->next) {
1134                        struct commit *c = list->item;
1135                        if (c->object.flags & (UNINTERESTING | TREESAME))
1136                                continue;
1137                        update_treesame(revs, c);
1138                }
1139
1140        revs->commits = newlist;
1141        return 0;
1142}
1143
1144/*
1145 * Add an entry to refs->cmdline with the specified information.
1146 * *name is copied.
1147 */
1148static void add_rev_cmdline(struct rev_info *revs,
1149                            struct object *item,
1150                            const char *name,
1151                            int whence,
1152                            unsigned flags)
1153{
1154        struct rev_cmdline_info *info = &revs->cmdline;
1155        unsigned int nr = info->nr;
1156
1157        ALLOC_GROW(info->rev, nr + 1, info->alloc);
1158        info->rev[nr].item = item;
1159        info->rev[nr].name = xstrdup(name);
1160        info->rev[nr].whence = whence;
1161        info->rev[nr].flags = flags;
1162        info->nr++;
1163}
1164
1165static void add_rev_cmdline_list(struct rev_info *revs,
1166                                 struct commit_list *commit_list,
1167                                 int whence,
1168                                 unsigned flags)
1169{
1170        while (commit_list) {
1171                struct object *object = &commit_list->item->object;
1172                add_rev_cmdline(revs, object, oid_to_hex(&object->oid),
1173                                whence, flags);
1174                commit_list = commit_list->next;
1175        }
1176}
1177
1178struct all_refs_cb {
1179        int all_flags;
1180        int warned_bad_reflog;
1181        struct rev_info *all_revs;
1182        const char *name_for_errormsg;
1183        struct ref_store *refs;
1184};
1185
1186int ref_excluded(struct string_list *ref_excludes, const char *path)
1187{
1188        struct string_list_item *item;
1189
1190        if (!ref_excludes)
1191                return 0;
1192        for_each_string_list_item(item, ref_excludes) {
1193                if (!wildmatch(item->string, path, 0))
1194                        return 1;
1195        }
1196        return 0;
1197}
1198
1199static int handle_one_ref(const char *path, const struct object_id *oid,
1200                          int flag, void *cb_data)
1201{
1202        struct all_refs_cb *cb = cb_data;
1203        struct object *object;
1204
1205        if (ref_excluded(cb->all_revs->ref_excludes, path))
1206            return 0;
1207
1208        object = get_reference(cb->all_revs, path, oid, cb->all_flags);
1209        add_rev_cmdline(cb->all_revs, object, path, REV_CMD_REF, cb->all_flags);
1210        add_pending_oid(cb->all_revs, path, oid, cb->all_flags);
1211        return 0;
1212}
1213
1214static void init_all_refs_cb(struct all_refs_cb *cb, struct rev_info *revs,
1215        unsigned flags)
1216{
1217        cb->all_revs = revs;
1218        cb->all_flags = flags;
1219        revs->rev_input_given = 1;
1220        cb->refs = NULL;
1221}
1222
1223void clear_ref_exclusion(struct string_list **ref_excludes_p)
1224{
1225        if (*ref_excludes_p) {
1226                string_list_clear(*ref_excludes_p, 0);
1227                free(*ref_excludes_p);
1228        }
1229        *ref_excludes_p = NULL;
1230}
1231
1232void add_ref_exclusion(struct string_list **ref_excludes_p, const char *exclude)
1233{
1234        if (!*ref_excludes_p) {
1235                *ref_excludes_p = xcalloc(1, sizeof(**ref_excludes_p));
1236                (*ref_excludes_p)->strdup_strings = 1;
1237        }
1238        string_list_append(*ref_excludes_p, exclude);
1239}
1240
1241static void handle_refs(struct ref_store *refs,
1242                        struct rev_info *revs, unsigned flags,
1243                        int (*for_each)(struct ref_store *, each_ref_fn, void *))
1244{
1245        struct all_refs_cb cb;
1246
1247        if (!refs) {
1248                /* this could happen with uninitialized submodules */
1249                return;
1250        }
1251
1252        init_all_refs_cb(&cb, revs, flags);
1253        for_each(refs, handle_one_ref, &cb);
1254}
1255
1256static void handle_one_reflog_commit(struct object_id *oid, void *cb_data)
1257{
1258        struct all_refs_cb *cb = cb_data;
1259        if (!is_null_oid(oid)) {
1260                struct object *o = parse_object(the_repository, oid);
1261                if (o) {
1262                        o->flags |= cb->all_flags;
1263                        /* ??? CMDLINEFLAGS ??? */
1264                        add_pending_object(cb->all_revs, o, "");
1265                }
1266                else if (!cb->warned_bad_reflog) {
1267                        warning("reflog of '%s' references pruned commits",
1268                                cb->name_for_errormsg);
1269                        cb->warned_bad_reflog = 1;
1270                }
1271        }
1272}
1273
1274static int handle_one_reflog_ent(struct object_id *ooid, struct object_id *noid,
1275                const char *email, timestamp_t timestamp, int tz,
1276                const char *message, void *cb_data)
1277{
1278        handle_one_reflog_commit(ooid, cb_data);
1279        handle_one_reflog_commit(noid, cb_data);
1280        return 0;
1281}
1282
1283static int handle_one_reflog(const char *path, const struct object_id *oid,
1284                             int flag, void *cb_data)
1285{
1286        struct all_refs_cb *cb = cb_data;
1287        cb->warned_bad_reflog = 0;
1288        cb->name_for_errormsg = path;
1289        refs_for_each_reflog_ent(cb->refs, path,
1290                                 handle_one_reflog_ent, cb_data);
1291        return 0;
1292}
1293
1294static void add_other_reflogs_to_pending(struct all_refs_cb *cb)
1295{
1296        struct worktree **worktrees, **p;
1297
1298        worktrees = get_worktrees(0);
1299        for (p = worktrees; *p; p++) {
1300                struct worktree *wt = *p;
1301
1302                if (wt->is_current)
1303                        continue;
1304
1305                cb->refs = get_worktree_ref_store(wt);
1306                refs_for_each_reflog(cb->refs,
1307                                     handle_one_reflog,
1308                                     cb);
1309        }
1310        free_worktrees(worktrees);
1311}
1312
1313void add_reflogs_to_pending(struct rev_info *revs, unsigned flags)
1314{
1315        struct all_refs_cb cb;
1316
1317        cb.all_revs = revs;
1318        cb.all_flags = flags;
1319        cb.refs = get_main_ref_store(the_repository);
1320        for_each_reflog(handle_one_reflog, &cb);
1321
1322        if (!revs->single_worktree)
1323                add_other_reflogs_to_pending(&cb);
1324}
1325
1326static void add_cache_tree(struct cache_tree *it, struct rev_info *revs,
1327                           struct strbuf *path)
1328{
1329        size_t baselen = path->len;
1330        int i;
1331
1332        if (it->entry_count >= 0) {
1333                struct tree *tree = lookup_tree(the_repository, &it->oid);
1334                add_pending_object_with_path(revs, &tree->object, "",
1335                                             040000, path->buf);
1336        }
1337
1338        for (i = 0; i < it->subtree_nr; i++) {
1339                struct cache_tree_sub *sub = it->down[i];
1340                strbuf_addf(path, "%s%s", baselen ? "/" : "", sub->name);
1341                add_cache_tree(sub->cache_tree, revs, path);
1342                strbuf_setlen(path, baselen);
1343        }
1344
1345}
1346
1347static void do_add_index_objects_to_pending(struct rev_info *revs,
1348                                            struct index_state *istate)
1349{
1350        int i;
1351
1352        for (i = 0; i < istate->cache_nr; i++) {
1353                struct cache_entry *ce = istate->cache[i];
1354                struct blob *blob;
1355
1356                if (S_ISGITLINK(ce->ce_mode))
1357                        continue;
1358
1359                blob = lookup_blob(the_repository, &ce->oid);
1360                if (!blob)
1361                        die("unable to add index blob to traversal");
1362                add_pending_object_with_path(revs, &blob->object, "",
1363                                             ce->ce_mode, ce->name);
1364        }
1365
1366        if (istate->cache_tree) {
1367                struct strbuf path = STRBUF_INIT;
1368                add_cache_tree(istate->cache_tree, revs, &path);
1369                strbuf_release(&path);
1370        }
1371}
1372
1373void add_index_objects_to_pending(struct rev_info *revs, unsigned int flags)
1374{
1375        struct worktree **worktrees, **p;
1376
1377        read_cache();
1378        do_add_index_objects_to_pending(revs, &the_index);
1379
1380        if (revs->single_worktree)
1381                return;
1382
1383        worktrees = get_worktrees(0);
1384        for (p = worktrees; *p; p++) {
1385                struct worktree *wt = *p;
1386                struct index_state istate = { NULL };
1387
1388                if (wt->is_current)
1389                        continue; /* current index already taken care of */
1390
1391                if (read_index_from(&istate,
1392                                    worktree_git_path(wt, "index"),
1393                                    get_worktree_git_dir(wt)) > 0)
1394                        do_add_index_objects_to_pending(revs, &istate);
1395                discard_index(&istate);
1396        }
1397        free_worktrees(worktrees);
1398}
1399
1400static int add_parents_only(struct rev_info *revs, const char *arg_, int flags,
1401                            int exclude_parent)
1402{
1403        struct object_id oid;
1404        struct object *it;
1405        struct commit *commit;
1406        struct commit_list *parents;
1407        int parent_number;
1408        const char *arg = arg_;
1409
1410        if (*arg == '^') {
1411                flags ^= UNINTERESTING | BOTTOM;
1412                arg++;
1413        }
1414        if (get_oid_committish(arg, &oid))
1415                return 0;
1416        while (1) {
1417                it = get_reference(revs, arg, &oid, 0);
1418                if (!it && revs->ignore_missing)
1419                        return 0;
1420                if (it->type != OBJ_TAG)
1421                        break;
1422                if (!((struct tag*)it)->tagged)
1423                        return 0;
1424                oidcpy(&oid, &((struct tag*)it)->tagged->oid);
1425        }
1426        if (it->type != OBJ_COMMIT)
1427                return 0;
1428        commit = (struct commit *)it;
1429        if (exclude_parent &&
1430            exclude_parent > commit_list_count(commit->parents))
1431                return 0;
1432        for (parents = commit->parents, parent_number = 1;
1433             parents;
1434             parents = parents->next, parent_number++) {
1435                if (exclude_parent && parent_number != exclude_parent)
1436                        continue;
1437
1438                it = &parents->item->object;
1439                it->flags |= flags;
1440                add_rev_cmdline(revs, it, arg_, REV_CMD_PARENTS_ONLY, flags);
1441                add_pending_object(revs, it, arg);
1442        }
1443        return 1;
1444}
1445
1446void init_revisions(struct rev_info *revs, const char *prefix)
1447{
1448        memset(revs, 0, sizeof(*revs));
1449
1450        revs->abbrev = DEFAULT_ABBREV;
1451        revs->ignore_merges = 1;
1452        revs->simplify_history = 1;
1453        revs->pruning.flags.recursive = 1;
1454        revs->pruning.flags.quick = 1;
1455        revs->pruning.add_remove = file_add_remove;
1456        revs->pruning.change = file_change;
1457        revs->pruning.change_fn_data = revs;
1458        revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
1459        revs->dense = 1;
1460        revs->prefix = prefix;
1461        revs->max_age = -1;
1462        revs->min_age = -1;
1463        revs->skip_count = -1;
1464        revs->max_count = -1;
1465        revs->max_parents = -1;
1466        revs->expand_tabs_in_log = -1;
1467
1468        revs->commit_format = CMIT_FMT_DEFAULT;
1469        revs->expand_tabs_in_log_default = 8;
1470
1471        init_grep_defaults();
1472        grep_init(&revs->grep_filter, prefix);
1473        revs->grep_filter.status_only = 1;
1474
1475        diff_setup(&revs->diffopt);
1476        if (prefix && !revs->diffopt.prefix) {
1477                revs->diffopt.prefix = prefix;
1478                revs->diffopt.prefix_length = strlen(prefix);
1479        }
1480
1481        revs->notes_opt.use_default_notes = -1;
1482}
1483
1484static void add_pending_commit_list(struct rev_info *revs,
1485                                    struct commit_list *commit_list,
1486                                    unsigned int flags)
1487{
1488        while (commit_list) {
1489                struct object *object = &commit_list->item->object;
1490                object->flags |= flags;
1491                add_pending_object(revs, object, oid_to_hex(&object->oid));
1492                commit_list = commit_list->next;
1493        }
1494}
1495
1496static void prepare_show_merge(struct rev_info *revs)
1497{
1498        struct commit_list *bases;
1499        struct commit *head, *other;
1500        struct object_id oid;
1501        const char **prune = NULL;
1502        int i, prune_num = 1; /* counting terminating NULL */
1503
1504        if (get_oid("HEAD", &oid))
1505                die("--merge without HEAD?");
1506        head = lookup_commit_or_die(&oid, "HEAD");
1507        if (get_oid("MERGE_HEAD", &oid))
1508                die("--merge without MERGE_HEAD?");
1509        other = lookup_commit_or_die(&oid, "MERGE_HEAD");
1510        add_pending_object(revs, &head->object, "HEAD");
1511        add_pending_object(revs, &other->object, "MERGE_HEAD");
1512        bases = get_merge_bases(head, other);
1513        add_rev_cmdline_list(revs, bases, REV_CMD_MERGE_BASE, UNINTERESTING | BOTTOM);
1514        add_pending_commit_list(revs, bases, UNINTERESTING | BOTTOM);
1515        free_commit_list(bases);
1516        head->object.flags |= SYMMETRIC_LEFT;
1517
1518        if (!active_nr)
1519                read_cache();
1520        for (i = 0; i < active_nr; i++) {
1521                const struct cache_entry *ce = active_cache[i];
1522                if (!ce_stage(ce))
1523                        continue;
1524                if (ce_path_match(&the_index, ce, &revs->prune_data, NULL)) {
1525                        prune_num++;
1526                        REALLOC_ARRAY(prune, prune_num);
1527                        prune[prune_num-2] = ce->name;
1528                        prune[prune_num-1] = NULL;
1529                }
1530                while ((i+1 < active_nr) &&
1531                       ce_same_name(ce, active_cache[i+1]))
1532                        i++;
1533        }
1534        clear_pathspec(&revs->prune_data);
1535        parse_pathspec(&revs->prune_data, PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1536                       PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH, "", prune);
1537        revs->limited = 1;
1538}
1539
1540static int dotdot_missing(const char *arg, char *dotdot,
1541                          struct rev_info *revs, int symmetric)
1542{
1543        if (revs->ignore_missing)
1544                return 0;
1545        /* de-munge so we report the full argument */
1546        *dotdot = '.';
1547        die(symmetric
1548            ? "Invalid symmetric difference expression %s"
1549            : "Invalid revision range %s", arg);
1550}
1551
1552static int handle_dotdot_1(const char *arg, char *dotdot,
1553                           struct rev_info *revs, int flags,
1554                           int cant_be_filename,
1555                           struct object_context *a_oc,
1556                           struct object_context *b_oc)
1557{
1558        const char *a_name, *b_name;
1559        struct object_id a_oid, b_oid;
1560        struct object *a_obj, *b_obj;
1561        unsigned int a_flags, b_flags;
1562        int symmetric = 0;
1563        unsigned int flags_exclude = flags ^ (UNINTERESTING | BOTTOM);
1564        unsigned int oc_flags = GET_OID_COMMITTISH | GET_OID_RECORD_PATH;
1565
1566        a_name = arg;
1567        if (!*a_name)
1568                a_name = "HEAD";
1569
1570        b_name = dotdot + 2;
1571        if (*b_name == '.') {
1572                symmetric = 1;
1573                b_name++;
1574        }
1575        if (!*b_name)
1576                b_name = "HEAD";
1577
1578        if (get_oid_with_context(a_name, oc_flags, &a_oid, a_oc) ||
1579            get_oid_with_context(b_name, oc_flags, &b_oid, b_oc))
1580                return -1;
1581
1582        if (!cant_be_filename) {
1583                *dotdot = '.';
1584                verify_non_filename(revs->prefix, arg);
1585                *dotdot = '\0';
1586        }
1587
1588        a_obj = parse_object(the_repository, &a_oid);
1589        b_obj = parse_object(the_repository, &b_oid);
1590        if (!a_obj || !b_obj)
1591                return dotdot_missing(arg, dotdot, revs, symmetric);
1592
1593        if (!symmetric) {
1594                /* just A..B */
1595                b_flags = flags;
1596                a_flags = flags_exclude;
1597        } else {
1598                /* A...B -- find merge bases between the two */
1599                struct commit *a, *b;
1600                struct commit_list *exclude;
1601
1602                a = lookup_commit_reference(the_repository, &a_obj->oid);
1603                b = lookup_commit_reference(the_repository, &b_obj->oid);
1604                if (!a || !b)
1605                        return dotdot_missing(arg, dotdot, revs, symmetric);
1606
1607                exclude = get_merge_bases(a, b);
1608                add_rev_cmdline_list(revs, exclude, REV_CMD_MERGE_BASE,
1609                                     flags_exclude);
1610                add_pending_commit_list(revs, exclude, flags_exclude);
1611                free_commit_list(exclude);
1612
1613                b_flags = flags;
1614                a_flags = flags | SYMMETRIC_LEFT;
1615        }
1616
1617        a_obj->flags |= a_flags;
1618        b_obj->flags |= b_flags;
1619        add_rev_cmdline(revs, a_obj, a_name, REV_CMD_LEFT, a_flags);
1620        add_rev_cmdline(revs, b_obj, b_name, REV_CMD_RIGHT, b_flags);
1621        add_pending_object_with_path(revs, a_obj, a_name, a_oc->mode, a_oc->path);
1622        add_pending_object_with_path(revs, b_obj, b_name, b_oc->mode, b_oc->path);
1623        return 0;
1624}
1625
1626static int handle_dotdot(const char *arg,
1627                         struct rev_info *revs, int flags,
1628                         int cant_be_filename)
1629{
1630        struct object_context a_oc, b_oc;
1631        char *dotdot = strstr(arg, "..");
1632        int ret;
1633
1634        if (!dotdot)
1635                return -1;
1636
1637        memset(&a_oc, 0, sizeof(a_oc));
1638        memset(&b_oc, 0, sizeof(b_oc));
1639
1640        *dotdot = '\0';
1641        ret = handle_dotdot_1(arg, dotdot, revs, flags, cant_be_filename,
1642                              &a_oc, &b_oc);
1643        *dotdot = '.';
1644
1645        free(a_oc.path);
1646        free(b_oc.path);
1647
1648        return ret;
1649}
1650
1651int handle_revision_arg(const char *arg_, struct rev_info *revs, int flags, unsigned revarg_opt)
1652{
1653        struct object_context oc;
1654        char *mark;
1655        struct object *object;
1656        struct object_id oid;
1657        int local_flags;
1658        const char *arg = arg_;
1659        int cant_be_filename = revarg_opt & REVARG_CANNOT_BE_FILENAME;
1660        unsigned get_sha1_flags = GET_OID_RECORD_PATH;
1661
1662        flags = flags & UNINTERESTING ? flags | BOTTOM : flags & ~BOTTOM;
1663
1664        if (!cant_be_filename && !strcmp(arg, "..")) {
1665                /*
1666                 * Just ".."?  That is not a range but the
1667                 * pathspec for the parent directory.
1668                 */
1669                return -1;
1670        }
1671
1672        if (!handle_dotdot(arg, revs, flags, revarg_opt))
1673                return 0;
1674
1675        mark = strstr(arg, "^@");
1676        if (mark && !mark[2]) {
1677                *mark = 0;
1678                if (add_parents_only(revs, arg, flags, 0))
1679                        return 0;
1680                *mark = '^';
1681        }
1682        mark = strstr(arg, "^!");
1683        if (mark && !mark[2]) {
1684                *mark = 0;
1685                if (!add_parents_only(revs, arg, flags ^ (UNINTERESTING | BOTTOM), 0))
1686                        *mark = '^';
1687        }
1688        mark = strstr(arg, "^-");
1689        if (mark) {
1690                int exclude_parent = 1;
1691
1692                if (mark[2]) {
1693                        char *end;
1694                        exclude_parent = strtoul(mark + 2, &end, 10);
1695                        if (*end != '\0' || !exclude_parent)
1696                                return -1;
1697                }
1698
1699                *mark = 0;
1700                if (!add_parents_only(revs, arg, flags ^ (UNINTERESTING | BOTTOM), exclude_parent))
1701                        *mark = '^';
1702        }
1703
1704        local_flags = 0;
1705        if (*arg == '^') {
1706                local_flags = UNINTERESTING | BOTTOM;
1707                arg++;
1708        }
1709
1710        if (revarg_opt & REVARG_COMMITTISH)
1711                get_sha1_flags |= GET_OID_COMMITTISH;
1712
1713        if (get_oid_with_context(arg, get_sha1_flags, &oid, &oc))
1714                return revs->ignore_missing ? 0 : -1;
1715        if (!cant_be_filename)
1716                verify_non_filename(revs->prefix, arg);
1717        object = get_reference(revs, arg, &oid, flags ^ local_flags);
1718        add_rev_cmdline(revs, object, arg_, REV_CMD_REV, flags ^ local_flags);
1719        add_pending_object_with_path(revs, object, arg, oc.mode, oc.path);
1720        free(oc.path);
1721        return 0;
1722}
1723
1724static void read_pathspec_from_stdin(struct rev_info *revs, struct strbuf *sb,
1725                                     struct argv_array *prune)
1726{
1727        while (strbuf_getline(sb, stdin) != EOF)
1728                argv_array_push(prune, sb->buf);
1729}
1730
1731static void read_revisions_from_stdin(struct rev_info *revs,
1732                                      struct argv_array *prune)
1733{
1734        struct strbuf sb;
1735        int seen_dashdash = 0;
1736        int save_warning;
1737
1738        save_warning = warn_on_object_refname_ambiguity;
1739        warn_on_object_refname_ambiguity = 0;
1740
1741        strbuf_init(&sb, 1000);
1742        while (strbuf_getline(&sb, stdin) != EOF) {
1743                int len = sb.len;
1744                if (!len)
1745                        break;
1746                if (sb.buf[0] == '-') {
1747                        if (len == 2 && sb.buf[1] == '-') {
1748                                seen_dashdash = 1;
1749                                break;
1750                        }
1751                        die("options not supported in --stdin mode");
1752                }
1753                if (handle_revision_arg(sb.buf, revs, 0,
1754                                        REVARG_CANNOT_BE_FILENAME))
1755                        die("bad revision '%s'", sb.buf);
1756        }
1757        if (seen_dashdash)
1758                read_pathspec_from_stdin(revs, &sb, prune);
1759
1760        strbuf_release(&sb);
1761        warn_on_object_refname_ambiguity = save_warning;
1762}
1763
1764static void add_grep(struct rev_info *revs, const char *ptn, enum grep_pat_token what)
1765{
1766        append_grep_pattern(&revs->grep_filter, ptn, "command line", 0, what);
1767}
1768
1769static void add_header_grep(struct rev_info *revs, enum grep_header_field field, const char *pattern)
1770{
1771        append_header_grep_pattern(&revs->grep_filter, field, pattern);
1772}
1773
1774static void add_message_grep(struct rev_info *revs, const char *pattern)
1775{
1776        add_grep(revs, pattern, GREP_PATTERN_BODY);
1777}
1778
1779static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv,
1780                               int *unkc, const char **unkv)
1781{
1782        const char *arg = argv[0];
1783        const char *optarg;
1784        int argcount;
1785        const unsigned hexsz = the_hash_algo->hexsz;
1786
1787        /* pseudo revision arguments */
1788        if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") ||
1789            !strcmp(arg, "--tags") || !strcmp(arg, "--remotes") ||
1790            !strcmp(arg, "--reflog") || !strcmp(arg, "--not") ||
1791            !strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk") ||
1792            !strcmp(arg, "--bisect") || starts_with(arg, "--glob=") ||
1793            !strcmp(arg, "--indexed-objects") ||
1794            starts_with(arg, "--exclude=") ||
1795            starts_with(arg, "--branches=") || starts_with(arg, "--tags=") ||
1796            starts_with(arg, "--remotes=") || starts_with(arg, "--no-walk="))
1797        {
1798                unkv[(*unkc)++] = arg;
1799                return 1;
1800        }
1801
1802        if ((argcount = parse_long_opt("max-count", argv, &optarg))) {
1803                revs->max_count = atoi(optarg);
1804                revs->no_walk = 0;
1805                return argcount;
1806        } else if ((argcount = parse_long_opt("skip", argv, &optarg))) {
1807                revs->skip_count = atoi(optarg);
1808                return argcount;
1809        } else if ((*arg == '-') && isdigit(arg[1])) {
1810                /* accept -<digit>, like traditional "head" */
1811                if (strtol_i(arg + 1, 10, &revs->max_count) < 0 ||
1812                    revs->max_count < 0)
1813                        die("'%s': not a non-negative integer", arg + 1);
1814                revs->no_walk = 0;
1815        } else if (!strcmp(arg, "-n")) {
1816                if (argc <= 1)
1817                        return error("-n requires an argument");
1818                revs->max_count = atoi(argv[1]);
1819                revs->no_walk = 0;
1820                return 2;
1821        } else if (skip_prefix(arg, "-n", &optarg)) {
1822                revs->max_count = atoi(optarg);
1823                revs->no_walk = 0;
1824        } else if ((argcount = parse_long_opt("max-age", argv, &optarg))) {
1825                revs->max_age = atoi(optarg);
1826                return argcount;
1827        } else if ((argcount = parse_long_opt("since", argv, &optarg))) {
1828                revs->max_age = approxidate(optarg);
1829                return argcount;
1830        } else if ((argcount = parse_long_opt("after", argv, &optarg))) {
1831                revs->max_age = approxidate(optarg);
1832                return argcount;
1833        } else if ((argcount = parse_long_opt("min-age", argv, &optarg))) {
1834                revs->min_age = atoi(optarg);
1835                return argcount;
1836        } else if ((argcount = parse_long_opt("before", argv, &optarg))) {
1837                revs->min_age = approxidate(optarg);
1838                return argcount;
1839        } else if ((argcount = parse_long_opt("until", argv, &optarg))) {
1840                revs->min_age = approxidate(optarg);
1841                return argcount;
1842        } else if (!strcmp(arg, "--first-parent")) {
1843                revs->first_parent_only = 1;
1844        } else if (!strcmp(arg, "--ancestry-path")) {
1845                revs->ancestry_path = 1;
1846                revs->simplify_history = 0;
1847                revs->limited = 1;
1848        } else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) {
1849                init_reflog_walk(&revs->reflog_info);
1850        } else if (!strcmp(arg, "--default")) {
1851                if (argc <= 1)
1852                        return error("bad --default argument");
1853                revs->def = argv[1];
1854                return 2;
1855        } else if (!strcmp(arg, "--merge")) {
1856                revs->show_merge = 1;
1857        } else if (!strcmp(arg, "--topo-order")) {
1858                revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
1859                revs->topo_order = 1;
1860        } else if (!strcmp(arg, "--simplify-merges")) {
1861                revs->simplify_merges = 1;
1862                revs->topo_order = 1;
1863                revs->rewrite_parents = 1;
1864                revs->simplify_history = 0;
1865                revs->limited = 1;
1866        } else if (!strcmp(arg, "--simplify-by-decoration")) {
1867                revs->simplify_merges = 1;
1868                revs->topo_order = 1;
1869                revs->rewrite_parents = 1;
1870                revs->simplify_history = 0;
1871                revs->simplify_by_decoration = 1;
1872                revs->limited = 1;
1873                revs->prune = 1;
1874                load_ref_decorations(NULL, DECORATE_SHORT_REFS);
1875        } else if (!strcmp(arg, "--date-order")) {
1876                revs->sort_order = REV_SORT_BY_COMMIT_DATE;
1877                revs->topo_order = 1;
1878        } else if (!strcmp(arg, "--author-date-order")) {
1879                revs->sort_order = REV_SORT_BY_AUTHOR_DATE;
1880                revs->topo_order = 1;
1881        } else if (!strcmp(arg, "--early-output")) {
1882                revs->early_output = 100;
1883                revs->topo_order = 1;
1884        } else if (skip_prefix(arg, "--early-output=", &optarg)) {
1885                if (strtoul_ui(optarg, 10, &revs->early_output) < 0)
1886                        die("'%s': not a non-negative integer", optarg);
1887                revs->topo_order = 1;
1888        } else if (!strcmp(arg, "--parents")) {
1889                revs->rewrite_parents = 1;
1890                revs->print_parents = 1;
1891        } else if (!strcmp(arg, "--dense")) {
1892                revs->dense = 1;
1893        } else if (!strcmp(arg, "--sparse")) {
1894                revs->dense = 0;
1895        } else if (!strcmp(arg, "--in-commit-order")) {
1896                revs->tree_blobs_in_commit_order = 1;
1897        } else if (!strcmp(arg, "--remove-empty")) {
1898                revs->remove_empty_trees = 1;
1899        } else if (!strcmp(arg, "--merges")) {
1900                revs->min_parents = 2;
1901        } else if (!strcmp(arg, "--no-merges")) {
1902                revs->max_parents = 1;
1903        } else if (skip_prefix(arg, "--min-parents=", &optarg)) {
1904                revs->min_parents = atoi(optarg);
1905        } else if (!strcmp(arg, "--no-min-parents")) {
1906                revs->min_parents = 0;
1907        } else if (skip_prefix(arg, "--max-parents=", &optarg)) {
1908                revs->max_parents = atoi(optarg);
1909        } else if (!strcmp(arg, "--no-max-parents")) {
1910                revs->max_parents = -1;
1911        } else if (!strcmp(arg, "--boundary")) {
1912                revs->boundary = 1;
1913        } else if (!strcmp(arg, "--left-right")) {
1914                revs->left_right = 1;
1915        } else if (!strcmp(arg, "--left-only")) {
1916                if (revs->right_only)
1917                        die("--left-only is incompatible with --right-only"
1918                            " or --cherry");
1919                revs->left_only = 1;
1920        } else if (!strcmp(arg, "--right-only")) {
1921                if (revs->left_only)
1922                        die("--right-only is incompatible with --left-only");
1923                revs->right_only = 1;
1924        } else if (!strcmp(arg, "--cherry")) {
1925                if (revs->left_only)
1926                        die("--cherry is incompatible with --left-only");
1927                revs->cherry_mark = 1;
1928                revs->right_only = 1;
1929                revs->max_parents = 1;
1930                revs->limited = 1;
1931        } else if (!strcmp(arg, "--count")) {
1932                revs->count = 1;
1933        } else if (!strcmp(arg, "--cherry-mark")) {
1934                if (revs->cherry_pick)
1935                        die("--cherry-mark is incompatible with --cherry-pick");
1936                revs->cherry_mark = 1;
1937                revs->limited = 1; /* needs limit_list() */
1938        } else if (!strcmp(arg, "--cherry-pick")) {
1939                if (revs->cherry_mark)
1940                        die("--cherry-pick is incompatible with --cherry-mark");
1941                revs->cherry_pick = 1;
1942                revs->limited = 1;
1943        } else if (!strcmp(arg, "--objects")) {
1944                revs->tag_objects = 1;
1945                revs->tree_objects = 1;
1946                revs->blob_objects = 1;
1947        } else if (!strcmp(arg, "--objects-edge")) {
1948                revs->tag_objects = 1;
1949                revs->tree_objects = 1;
1950                revs->blob_objects = 1;
1951                revs->edge_hint = 1;
1952        } else if (!strcmp(arg, "--objects-edge-aggressive")) {
1953                revs->tag_objects = 1;
1954                revs->tree_objects = 1;
1955                revs->blob_objects = 1;
1956                revs->edge_hint = 1;
1957                revs->edge_hint_aggressive = 1;
1958        } else if (!strcmp(arg, "--verify-objects")) {
1959                revs->tag_objects = 1;
1960                revs->tree_objects = 1;
1961                revs->blob_objects = 1;
1962                revs->verify_objects = 1;
1963        } else if (!strcmp(arg, "--unpacked")) {
1964                revs->unpacked = 1;
1965        } else if (starts_with(arg, "--unpacked=")) {
1966                die("--unpacked=<packfile> no longer supported.");
1967        } else if (!strcmp(arg, "-r")) {
1968                revs->diff = 1;
1969                revs->diffopt.flags.recursive = 1;
1970        } else if (!strcmp(arg, "-t")) {
1971                revs->diff = 1;
1972                revs->diffopt.flags.recursive = 1;
1973                revs->diffopt.flags.tree_in_recursive = 1;
1974        } else if (!strcmp(arg, "-m")) {
1975                revs->ignore_merges = 0;
1976        } else if (!strcmp(arg, "-c")) {
1977                revs->diff = 1;
1978                revs->dense_combined_merges = 0;
1979                revs->combine_merges = 1;
1980        } else if (!strcmp(arg, "--cc")) {
1981                revs->diff = 1;
1982                revs->dense_combined_merges = 1;
1983                revs->combine_merges = 1;
1984        } else if (!strcmp(arg, "-v")) {
1985                revs->verbose_header = 1;
1986        } else if (!strcmp(arg, "--pretty")) {
1987                revs->verbose_header = 1;
1988                revs->pretty_given = 1;
1989                get_commit_format(NULL, revs);
1990        } else if (skip_prefix(arg, "--pretty=", &optarg) ||
1991                   skip_prefix(arg, "--format=", &optarg)) {
1992                /*
1993                 * Detached form ("--pretty X" as opposed to "--pretty=X")
1994                 * not allowed, since the argument is optional.
1995                 */
1996                revs->verbose_header = 1;
1997                revs->pretty_given = 1;
1998                get_commit_format(optarg, revs);
1999        } else if (!strcmp(arg, "--expand-tabs")) {
2000                revs->expand_tabs_in_log = 8;
2001        } else if (!strcmp(arg, "--no-expand-tabs")) {
2002                revs->expand_tabs_in_log = 0;
2003        } else if (skip_prefix(arg, "--expand-tabs=", &arg)) {
2004                int val;
2005                if (strtol_i(arg, 10, &val) < 0 || val < 0)
2006                        die("'%s': not a non-negative integer", arg);
2007                revs->expand_tabs_in_log = val;
2008        } else if (!strcmp(arg, "--show-notes") || !strcmp(arg, "--notes")) {
2009                revs->show_notes = 1;
2010                revs->show_notes_given = 1;
2011                revs->notes_opt.use_default_notes = 1;
2012        } else if (!strcmp(arg, "--show-signature")) {
2013                revs->show_signature = 1;
2014        } else if (!strcmp(arg, "--no-show-signature")) {
2015                revs->show_signature = 0;
2016        } else if (!strcmp(arg, "--show-linear-break")) {
2017                revs->break_bar = "                    ..........";
2018                revs->track_linear = 1;
2019                revs->track_first_time = 1;
2020        } else if (skip_prefix(arg, "--show-linear-break=", &optarg)) {
2021                revs->break_bar = xstrdup(optarg);
2022                revs->track_linear = 1;
2023                revs->track_first_time = 1;
2024        } else if (skip_prefix(arg, "--show-notes=", &optarg) ||
2025                   skip_prefix(arg, "--notes=", &optarg)) {
2026                struct strbuf buf = STRBUF_INIT;
2027                revs->show_notes = 1;
2028                revs->show_notes_given = 1;
2029                if (starts_with(arg, "--show-notes=") &&
2030                    revs->notes_opt.use_default_notes < 0)
2031                        revs->notes_opt.use_default_notes = 1;
2032                strbuf_addstr(&buf, optarg);
2033                expand_notes_ref(&buf);
2034                string_list_append(&revs->notes_opt.extra_notes_refs,
2035                                   strbuf_detach(&buf, NULL));
2036        } else if (!strcmp(arg, "--no-notes")) {
2037                revs->show_notes = 0;
2038                revs->show_notes_given = 1;
2039                revs->notes_opt.use_default_notes = -1;
2040                /* we have been strdup'ing ourselves, so trick
2041                 * string_list into free()ing strings */
2042                revs->notes_opt.extra_notes_refs.strdup_strings = 1;
2043                string_list_clear(&revs->notes_opt.extra_notes_refs, 0);
2044                revs->notes_opt.extra_notes_refs.strdup_strings = 0;
2045        } else if (!strcmp(arg, "--standard-notes")) {
2046                revs->show_notes_given = 1;
2047                revs->notes_opt.use_default_notes = 1;
2048        } else if (!strcmp(arg, "--no-standard-notes")) {
2049                revs->notes_opt.use_default_notes = 0;
2050        } else if (!strcmp(arg, "--oneline")) {
2051                revs->verbose_header = 1;
2052                get_commit_format("oneline", revs);
2053                revs->pretty_given = 1;
2054                revs->abbrev_commit = 1;
2055        } else if (!strcmp(arg, "--graph")) {
2056                revs->topo_order = 1;
2057                revs->rewrite_parents = 1;
2058                revs->graph = graph_init(revs);
2059        } else if (!strcmp(arg, "--root")) {
2060                revs->show_root_diff = 1;
2061        } else if (!strcmp(arg, "--no-commit-id")) {
2062                revs->no_commit_id = 1;
2063        } else if (!strcmp(arg, "--always")) {
2064                revs->always_show_header = 1;
2065        } else if (!strcmp(arg, "--no-abbrev")) {
2066                revs->abbrev = 0;
2067        } else if (!strcmp(arg, "--abbrev")) {
2068                revs->abbrev = DEFAULT_ABBREV;
2069        } else if (skip_prefix(arg, "--abbrev=", &optarg)) {
2070                revs->abbrev = strtoul(optarg, NULL, 10);
2071                if (revs->abbrev < MINIMUM_ABBREV)
2072                        revs->abbrev = MINIMUM_ABBREV;
2073                else if (revs->abbrev > hexsz)
2074                        revs->abbrev = hexsz;
2075        } else if (!strcmp(arg, "--abbrev-commit")) {
2076                revs->abbrev_commit = 1;
2077                revs->abbrev_commit_given = 1;
2078        } else if (!strcmp(arg, "--no-abbrev-commit")) {
2079                revs->abbrev_commit = 0;
2080        } else if (!strcmp(arg, "--full-diff")) {
2081                revs->diff = 1;
2082                revs->full_diff = 1;
2083        } else if (!strcmp(arg, "--full-history")) {
2084                revs->simplify_history = 0;
2085        } else if (!strcmp(arg, "--relative-date")) {
2086                revs->date_mode.type = DATE_RELATIVE;
2087                revs->date_mode_explicit = 1;
2088        } else if ((argcount = parse_long_opt("date", argv, &optarg))) {
2089                parse_date_format(optarg, &revs->date_mode);
2090                revs->date_mode_explicit = 1;
2091                return argcount;
2092        } else if (!strcmp(arg, "--log-size")) {
2093                revs->show_log_size = 1;
2094        }
2095        /*
2096         * Grepping the commit log
2097         */
2098        else if ((argcount = parse_long_opt("author", argv, &optarg))) {
2099                add_header_grep(revs, GREP_HEADER_AUTHOR, optarg);
2100                return argcount;
2101        } else if ((argcount = parse_long_opt("committer", argv, &optarg))) {
2102                add_header_grep(revs, GREP_HEADER_COMMITTER, optarg);
2103                return argcount;
2104        } else if ((argcount = parse_long_opt("grep-reflog", argv, &optarg))) {
2105                add_header_grep(revs, GREP_HEADER_REFLOG, optarg);
2106                return argcount;
2107        } else if ((argcount = parse_long_opt("grep", argv, &optarg))) {
2108                add_message_grep(revs, optarg);
2109                return argcount;
2110        } else if (!strcmp(arg, "--grep-debug")) {
2111                revs->grep_filter.debug = 1;
2112        } else if (!strcmp(arg, "--basic-regexp")) {
2113                revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_BRE;
2114        } else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) {
2115                revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_ERE;
2116        } else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) {
2117                revs->grep_filter.ignore_case = 1;
2118                revs->diffopt.pickaxe_opts |= DIFF_PICKAXE_IGNORE_CASE;
2119        } else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) {
2120                revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_FIXED;
2121        } else if (!strcmp(arg, "--perl-regexp") || !strcmp(arg, "-P")) {
2122                revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_PCRE;
2123        } else if (!strcmp(arg, "--all-match")) {
2124                revs->grep_filter.all_match = 1;
2125        } else if (!strcmp(arg, "--invert-grep")) {
2126                revs->invert_grep = 1;
2127        } else if ((argcount = parse_long_opt("encoding", argv, &optarg))) {
2128                if (strcmp(optarg, "none"))
2129                        git_log_output_encoding = xstrdup(optarg);
2130                else
2131                        git_log_output_encoding = "";
2132                return argcount;
2133        } else if (!strcmp(arg, "--reverse")) {
2134                revs->reverse ^= 1;
2135        } else if (!strcmp(arg, "--children")) {
2136                revs->children.name = "children";
2137                revs->limited = 1;
2138        } else if (!strcmp(arg, "--ignore-missing")) {
2139                revs->ignore_missing = 1;
2140        } else if (!strcmp(arg, "--exclude-promisor-objects")) {
2141                if (fetch_if_missing)
2142                        BUG("exclude_promisor_objects can only be used when fetch_if_missing is 0");
2143                revs->exclude_promisor_objects = 1;
2144        } else {
2145                int opts = diff_opt_parse(&revs->diffopt, argv, argc, revs->prefix);
2146                if (!opts)
2147                        unkv[(*unkc)++] = arg;
2148                return opts;
2149        }
2150        if (revs->graph && revs->track_linear)
2151                die("--show-linear-break and --graph are incompatible");
2152
2153        return 1;
2154}
2155
2156void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx,
2157                        const struct option *options,
2158                        const char * const usagestr[])
2159{
2160        int n = handle_revision_opt(revs, ctx->argc, ctx->argv,
2161                                    &ctx->cpidx, ctx->out);
2162        if (n <= 0) {
2163                error("unknown option `%s'", ctx->argv[0]);
2164                usage_with_options(usagestr, options);
2165        }
2166        ctx->argv += n;
2167        ctx->argc -= n;
2168}
2169
2170static int for_each_bisect_ref(struct ref_store *refs, each_ref_fn fn,
2171                               void *cb_data, const char *term)
2172{
2173        struct strbuf bisect_refs = STRBUF_INIT;
2174        int status;
2175        strbuf_addf(&bisect_refs, "refs/bisect/%s", term);
2176        status = refs_for_each_fullref_in(refs, bisect_refs.buf, fn, cb_data, 0);
2177        strbuf_release(&bisect_refs);
2178        return status;
2179}
2180
2181static int for_each_bad_bisect_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
2182{
2183        return for_each_bisect_ref(refs, fn, cb_data, term_bad);
2184}
2185
2186static int for_each_good_bisect_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
2187{
2188        return for_each_bisect_ref(refs, fn, cb_data, term_good);
2189}
2190
2191static int handle_revision_pseudo_opt(const char *submodule,
2192                                struct rev_info *revs,
2193                                int argc, const char **argv, int *flags)
2194{
2195        const char *arg = argv[0];
2196        const char *optarg;
2197        struct ref_store *refs;
2198        int argcount;
2199
2200        if (submodule) {
2201                /*
2202                 * We need some something like get_submodule_worktrees()
2203                 * before we can go through all worktrees of a submodule,
2204                 * .e.g with adding all HEADs from --all, which is not
2205                 * supported right now, so stick to single worktree.
2206                 */
2207                if (!revs->single_worktree)
2208                        BUG("--single-worktree cannot be used together with submodule");
2209                refs = get_submodule_ref_store(submodule);
2210        } else
2211                refs = get_main_ref_store(the_repository);
2212
2213        /*
2214         * NOTE!
2215         *
2216         * Commands like "git shortlog" will not accept the options below
2217         * unless parse_revision_opt queues them (as opposed to erroring
2218         * out).
2219         *
2220         * When implementing your new pseudo-option, remember to
2221         * register it in the list at the top of handle_revision_opt.
2222         */
2223        if (!strcmp(arg, "--all")) {
2224                handle_refs(refs, revs, *flags, refs_for_each_ref);
2225                handle_refs(refs, revs, *flags, refs_head_ref);
2226                if (!revs->single_worktree) {
2227                        struct all_refs_cb cb;
2228
2229                        init_all_refs_cb(&cb, revs, *flags);
2230                        other_head_refs(handle_one_ref, &cb);
2231                }
2232                clear_ref_exclusion(&revs->ref_excludes);
2233        } else if (!strcmp(arg, "--branches")) {
2234                handle_refs(refs, revs, *flags, refs_for_each_branch_ref);
2235                clear_ref_exclusion(&revs->ref_excludes);
2236        } else if (!strcmp(arg, "--bisect")) {
2237                read_bisect_terms(&term_bad, &term_good);
2238                handle_refs(refs, revs, *flags, for_each_bad_bisect_ref);
2239                handle_refs(refs, revs, *flags ^ (UNINTERESTING | BOTTOM),
2240                            for_each_good_bisect_ref);
2241                revs->bisect = 1;
2242        } else if (!strcmp(arg, "--tags")) {
2243                handle_refs(refs, revs, *flags, refs_for_each_tag_ref);
2244                clear_ref_exclusion(&revs->ref_excludes);
2245        } else if (!strcmp(arg, "--remotes")) {
2246                handle_refs(refs, revs, *flags, refs_for_each_remote_ref);
2247                clear_ref_exclusion(&revs->ref_excludes);
2248        } else if ((argcount = parse_long_opt("glob", argv, &optarg))) {
2249                struct all_refs_cb cb;
2250                init_all_refs_cb(&cb, revs, *flags);
2251                for_each_glob_ref(handle_one_ref, optarg, &cb);
2252                clear_ref_exclusion(&revs->ref_excludes);
2253                return argcount;
2254        } else if ((argcount = parse_long_opt("exclude", argv, &optarg))) {
2255                add_ref_exclusion(&revs->ref_excludes, optarg);
2256                return argcount;
2257        } else if (skip_prefix(arg, "--branches=", &optarg)) {
2258                struct all_refs_cb cb;
2259                init_all_refs_cb(&cb, revs, *flags);
2260                for_each_glob_ref_in(handle_one_ref, optarg, "refs/heads/", &cb);
2261                clear_ref_exclusion(&revs->ref_excludes);
2262        } else if (skip_prefix(arg, "--tags=", &optarg)) {
2263                struct all_refs_cb cb;
2264                init_all_refs_cb(&cb, revs, *flags);
2265                for_each_glob_ref_in(handle_one_ref, optarg, "refs/tags/", &cb);
2266                clear_ref_exclusion(&revs->ref_excludes);
2267        } else if (skip_prefix(arg, "--remotes=", &optarg)) {
2268                struct all_refs_cb cb;
2269                init_all_refs_cb(&cb, revs, *flags);
2270                for_each_glob_ref_in(handle_one_ref, optarg, "refs/remotes/", &cb);
2271                clear_ref_exclusion(&revs->ref_excludes);
2272        } else if (!strcmp(arg, "--reflog")) {
2273                add_reflogs_to_pending(revs, *flags);
2274        } else if (!strcmp(arg, "--indexed-objects")) {
2275                add_index_objects_to_pending(revs, *flags);
2276        } else if (!strcmp(arg, "--not")) {
2277                *flags ^= UNINTERESTING | BOTTOM;
2278        } else if (!strcmp(arg, "--no-walk")) {
2279                revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
2280        } else if (skip_prefix(arg, "--no-walk=", &optarg)) {
2281                /*
2282                 * Detached form ("--no-walk X" as opposed to "--no-walk=X")
2283                 * not allowed, since the argument is optional.
2284                 */
2285                if (!strcmp(optarg, "sorted"))
2286                        revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
2287                else if (!strcmp(optarg, "unsorted"))
2288                        revs->no_walk = REVISION_WALK_NO_WALK_UNSORTED;
2289                else
2290                        return error("invalid argument to --no-walk");
2291        } else if (!strcmp(arg, "--do-walk")) {
2292                revs->no_walk = 0;
2293        } else if (!strcmp(arg, "--single-worktree")) {
2294                revs->single_worktree = 1;
2295        } else {
2296                return 0;
2297        }
2298
2299        return 1;
2300}
2301
2302static void NORETURN diagnose_missing_default(const char *def)
2303{
2304        int flags;
2305        const char *refname;
2306
2307        refname = resolve_ref_unsafe(def, 0, NULL, &flags);
2308        if (!refname || !(flags & REF_ISSYMREF) || (flags & REF_ISBROKEN))
2309                die(_("your current branch appears to be broken"));
2310
2311        skip_prefix(refname, "refs/heads/", &refname);
2312        die(_("your current branch '%s' does not have any commits yet"),
2313            refname);
2314}
2315
2316/*
2317 * Parse revision information, filling in the "rev_info" structure,
2318 * and removing the used arguments from the argument list.
2319 *
2320 * Returns the number of arguments left that weren't recognized
2321 * (which are also moved to the head of the argument list)
2322 */
2323int setup_revisions(int argc, const char **argv, struct rev_info *revs, struct setup_revision_opt *opt)
2324{
2325        int i, flags, left, seen_dashdash, got_rev_arg = 0, revarg_opt;
2326        struct argv_array prune_data = ARGV_ARRAY_INIT;
2327        const char *submodule = NULL;
2328
2329        if (opt)
2330                submodule = opt->submodule;
2331
2332        /* First, search for "--" */
2333        if (opt && opt->assume_dashdash) {
2334                seen_dashdash = 1;
2335        } else {
2336                seen_dashdash = 0;
2337                for (i = 1; i < argc; i++) {
2338                        const char *arg = argv[i];
2339                        if (strcmp(arg, "--"))
2340                                continue;
2341                        argv[i] = NULL;
2342                        argc = i;
2343                        if (argv[i + 1])
2344                                argv_array_pushv(&prune_data, argv + i + 1);
2345                        seen_dashdash = 1;
2346                        break;
2347                }
2348        }
2349
2350        /* Second, deal with arguments and options */
2351        flags = 0;
2352        revarg_opt = opt ? opt->revarg_opt : 0;
2353        if (seen_dashdash)
2354                revarg_opt |= REVARG_CANNOT_BE_FILENAME;
2355        for (left = i = 1; i < argc; i++) {
2356                const char *arg = argv[i];
2357                if (*arg == '-') {
2358                        int opts;
2359
2360                        opts = handle_revision_pseudo_opt(submodule,
2361                                                revs, argc - i, argv + i,
2362                                                &flags);
2363                        if (opts > 0) {
2364                                i += opts - 1;
2365                                continue;
2366                        }
2367
2368                        if (!strcmp(arg, "--stdin")) {
2369                                if (revs->disable_stdin) {
2370                                        argv[left++] = arg;
2371                                        continue;
2372                                }
2373                                if (revs->read_from_stdin++)
2374                                        die("--stdin given twice?");
2375                                read_revisions_from_stdin(revs, &prune_data);
2376                                continue;
2377                        }
2378
2379                        opts = handle_revision_opt(revs, argc - i, argv + i, &left, argv);
2380                        if (opts > 0) {
2381                                i += opts - 1;
2382                                continue;
2383                        }
2384                        if (opts < 0)
2385                                exit(128);
2386                        continue;
2387                }
2388
2389
2390                if (handle_revision_arg(arg, revs, flags, revarg_opt)) {
2391                        int j;
2392                        if (seen_dashdash || *arg == '^')
2393                                die("bad revision '%s'", arg);
2394
2395                        /* If we didn't have a "--":
2396                         * (1) all filenames must exist;
2397                         * (2) all rev-args must not be interpretable
2398                         *     as a valid filename.
2399                         * but the latter we have checked in the main loop.
2400                         */
2401                        for (j = i; j < argc; j++)
2402                                verify_filename(revs->prefix, argv[j], j == i);
2403
2404                        argv_array_pushv(&prune_data, argv + i);
2405                        break;
2406                }
2407                else
2408                        got_rev_arg = 1;
2409        }
2410
2411        if (prune_data.argc) {
2412                /*
2413                 * If we need to introduce the magic "a lone ':' means no
2414                 * pathspec whatsoever", here is the place to do so.
2415                 *
2416                 * if (prune_data.nr == 1 && !strcmp(prune_data[0], ":")) {
2417                 *      prune_data.nr = 0;
2418                 *      prune_data.alloc = 0;
2419                 *      free(prune_data.path);
2420                 *      prune_data.path = NULL;
2421                 * } else {
2422                 *      terminate prune_data.alloc with NULL and
2423                 *      call init_pathspec() to set revs->prune_data here.
2424                 * }
2425                 */
2426                parse_pathspec(&revs->prune_data, 0, 0,
2427                               revs->prefix, prune_data.argv);
2428        }
2429        argv_array_clear(&prune_data);
2430
2431        if (revs->def == NULL)
2432                revs->def = opt ? opt->def : NULL;
2433        if (opt && opt->tweak)
2434                opt->tweak(revs, opt);
2435        if (revs->show_merge)
2436                prepare_show_merge(revs);
2437        if (revs->def && !revs->pending.nr && !revs->rev_input_given && !got_rev_arg) {
2438                struct object_id oid;
2439                struct object *object;
2440                struct object_context oc;
2441                if (get_oid_with_context(revs->def, 0, &oid, &oc))
2442                        diagnose_missing_default(revs->def);
2443                object = get_reference(revs, revs->def, &oid, 0);
2444                add_pending_object_with_mode(revs, object, revs->def, oc.mode);
2445        }
2446
2447        /* Did the user ask for any diff output? Run the diff! */
2448        if (revs->diffopt.output_format & ~DIFF_FORMAT_NO_OUTPUT)
2449                revs->diff = 1;
2450
2451        /* Pickaxe, diff-filter and rename following need diffs */
2452        if ((revs->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
2453            revs->diffopt.filter ||
2454            revs->diffopt.flags.follow_renames)
2455                revs->diff = 1;
2456
2457        if (revs->diffopt.objfind)
2458                revs->simplify_history = 0;
2459
2460        if (revs->topo_order && !generation_numbers_enabled(the_repository))
2461                revs->limited = 1;
2462
2463        if (revs->prune_data.nr) {
2464                copy_pathspec(&revs->pruning.pathspec, &revs->prune_data);
2465                /* Can't prune commits with rename following: the paths change.. */
2466                if (!revs->diffopt.flags.follow_renames)
2467                        revs->prune = 1;
2468                if (!revs->full_diff)
2469                        copy_pathspec(&revs->diffopt.pathspec,
2470                                      &revs->prune_data);
2471        }
2472        if (revs->combine_merges)
2473                revs->ignore_merges = 0;
2474        revs->diffopt.abbrev = revs->abbrev;
2475
2476        if (revs->line_level_traverse) {
2477                revs->limited = 1;
2478                revs->topo_order = 1;
2479        }
2480
2481        diff_setup_done(&revs->diffopt);
2482
2483        grep_commit_pattern_type(GREP_PATTERN_TYPE_UNSPECIFIED,
2484                                 &revs->grep_filter);
2485        compile_grep_patterns(&revs->grep_filter);
2486
2487        if (revs->reverse && revs->reflog_info)
2488                die("cannot combine --reverse with --walk-reflogs");
2489        if (revs->reflog_info && revs->limited)
2490                die("cannot combine --walk-reflogs with history-limiting options");
2491        if (revs->rewrite_parents && revs->children.name)
2492                die("cannot combine --parents and --children");
2493
2494        /*
2495         * Limitations on the graph functionality
2496         */
2497        if (revs->reverse && revs->graph)
2498                die("cannot combine --reverse with --graph");
2499
2500        if (revs->reflog_info && revs->graph)
2501                die("cannot combine --walk-reflogs with --graph");
2502        if (revs->no_walk && revs->graph)
2503                die("cannot combine --no-walk with --graph");
2504        if (!revs->reflog_info && revs->grep_filter.use_reflog_filter)
2505                die("cannot use --grep-reflog without --walk-reflogs");
2506
2507        if (revs->first_parent_only && revs->bisect)
2508                die(_("--first-parent is incompatible with --bisect"));
2509
2510        if (revs->expand_tabs_in_log < 0)
2511                revs->expand_tabs_in_log = revs->expand_tabs_in_log_default;
2512
2513        return left;
2514}
2515
2516static void add_child(struct rev_info *revs, struct commit *parent, struct commit *child)
2517{
2518        struct commit_list *l = xcalloc(1, sizeof(*l));
2519
2520        l->item = child;
2521        l->next = add_decoration(&revs->children, &parent->object, l);
2522}
2523
2524static int remove_duplicate_parents(struct rev_info *revs, struct commit *commit)
2525{
2526        struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
2527        struct commit_list **pp, *p;
2528        int surviving_parents;
2529
2530        /* Examine existing parents while marking ones we have seen... */
2531        pp = &commit->parents;
2532        surviving_parents = 0;
2533        while ((p = *pp) != NULL) {
2534                struct commit *parent = p->item;
2535                if (parent->object.flags & TMP_MARK) {
2536                        *pp = p->next;
2537                        if (ts)
2538                                compact_treesame(revs, commit, surviving_parents);
2539                        continue;
2540                }
2541                parent->object.flags |= TMP_MARK;
2542                surviving_parents++;
2543                pp = &p->next;
2544        }
2545        /* clear the temporary mark */
2546        for (p = commit->parents; p; p = p->next) {
2547                p->item->object.flags &= ~TMP_MARK;
2548        }
2549        /* no update_treesame() - removing duplicates can't affect TREESAME */
2550        return surviving_parents;
2551}
2552
2553struct merge_simplify_state {
2554        struct commit *simplified;
2555};
2556
2557static struct merge_simplify_state *locate_simplify_state(struct rev_info *revs, struct commit *commit)
2558{
2559        struct merge_simplify_state *st;
2560
2561        st = lookup_decoration(&revs->merge_simplification, &commit->object);
2562        if (!st) {
2563                st = xcalloc(1, sizeof(*st));
2564                add_decoration(&revs->merge_simplification, &commit->object, st);
2565        }
2566        return st;
2567}
2568
2569static int mark_redundant_parents(struct rev_info *revs, struct commit *commit)
2570{
2571        struct commit_list *h = reduce_heads(commit->parents);
2572        int i = 0, marked = 0;
2573        struct commit_list *po, *pn;
2574
2575        /* Want these for sanity-checking only */
2576        int orig_cnt = commit_list_count(commit->parents);
2577        int cnt = commit_list_count(h);
2578
2579        /*
2580         * Not ready to remove items yet, just mark them for now, based
2581         * on the output of reduce_heads(). reduce_heads outputs the reduced
2582         * set in its original order, so this isn't too hard.
2583         */
2584        po = commit->parents;
2585        pn = h;
2586        while (po) {
2587                if (pn && po->item == pn->item) {
2588                        pn = pn->next;
2589                        i++;
2590                } else {
2591                        po->item->object.flags |= TMP_MARK;
2592                        marked++;
2593                }
2594                po=po->next;
2595        }
2596
2597        if (i != cnt || cnt+marked != orig_cnt)
2598                die("mark_redundant_parents %d %d %d %d", orig_cnt, cnt, i, marked);
2599
2600        free_commit_list(h);
2601
2602        return marked;
2603}
2604
2605static int mark_treesame_root_parents(struct rev_info *revs, struct commit *commit)
2606{
2607        struct commit_list *p;
2608        int marked = 0;
2609
2610        for (p = commit->parents; p; p = p->next) {
2611                struct commit *parent = p->item;
2612                if (!parent->parents && (parent->object.flags & TREESAME)) {
2613                        parent->object.flags |= TMP_MARK;
2614                        marked++;
2615                }
2616        }
2617
2618        return marked;
2619}
2620
2621/*
2622 * Awkward naming - this means one parent we are TREESAME to.
2623 * cf mark_treesame_root_parents: root parents that are TREESAME (to an
2624 * empty tree). Better name suggestions?
2625 */
2626static int leave_one_treesame_to_parent(struct rev_info *revs, struct commit *commit)
2627{
2628        struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
2629        struct commit *unmarked = NULL, *marked = NULL;
2630        struct commit_list *p;
2631        unsigned n;
2632
2633        for (p = commit->parents, n = 0; p; p = p->next, n++) {
2634                if (ts->treesame[n]) {
2635                        if (p->item->object.flags & TMP_MARK) {
2636                                if (!marked)
2637                                        marked = p->item;
2638                        } else {
2639                                if (!unmarked) {
2640                                        unmarked = p->item;
2641                                        break;
2642                                }
2643                        }
2644                }
2645        }
2646
2647        /*
2648         * If we are TREESAME to a marked-for-deletion parent, but not to any
2649         * unmarked parents, unmark the first TREESAME parent. This is the
2650         * parent that the default simplify_history==1 scan would have followed,
2651         * and it doesn't make sense to omit that path when asking for a
2652         * simplified full history. Retaining it improves the chances of
2653         * understanding odd missed merges that took an old version of a file.
2654         *
2655         * Example:
2656         *
2657         *   I--------*X       A modified the file, but mainline merge X used
2658         *    \       /        "-s ours", so took the version from I. X is
2659         *     `-*A--'         TREESAME to I and !TREESAME to A.
2660         *
2661         * Default log from X would produce "I". Without this check,
2662         * --full-history --simplify-merges would produce "I-A-X", showing
2663         * the merge commit X and that it changed A, but not making clear that
2664         * it had just taken the I version. With this check, the topology above
2665         * is retained.
2666         *
2667         * Note that it is possible that the simplification chooses a different
2668         * TREESAME parent from the default, in which case this test doesn't
2669         * activate, and we _do_ drop the default parent. Example:
2670         *
2671         *   I------X         A modified the file, but it was reverted in B,
2672         *    \    /          meaning mainline merge X is TREESAME to both
2673         *    *A-*B           parents.
2674         *
2675         * Default log would produce "I" by following the first parent;
2676         * --full-history --simplify-merges will produce "I-A-B". But this is a
2677         * reasonable result - it presents a logical full history leading from
2678         * I to X, and X is not an important merge.
2679         */
2680        if (!unmarked && marked) {
2681                marked->object.flags &= ~TMP_MARK;
2682                return 1;
2683        }
2684
2685        return 0;
2686}
2687
2688static int remove_marked_parents(struct rev_info *revs, struct commit *commit)
2689{
2690        struct commit_list **pp, *p;
2691        int nth_parent, removed = 0;
2692
2693        pp = &commit->parents;
2694        nth_parent = 0;
2695        while ((p = *pp) != NULL) {
2696                struct commit *parent = p->item;
2697                if (parent->object.flags & TMP_MARK) {
2698                        parent->object.flags &= ~TMP_MARK;
2699                        *pp = p->next;
2700                        free(p);
2701                        removed++;
2702                        compact_treesame(revs, commit, nth_parent);
2703                        continue;
2704                }
2705                pp = &p->next;
2706                nth_parent++;
2707        }
2708
2709        /* Removing parents can only increase TREESAMEness */
2710        if (removed && !(commit->object.flags & TREESAME))
2711                update_treesame(revs, commit);
2712
2713        return nth_parent;
2714}
2715
2716static struct commit_list **simplify_one(struct rev_info *revs, struct commit *commit, struct commit_list **tail)
2717{
2718        struct commit_list *p;
2719        struct commit *parent;
2720        struct merge_simplify_state *st, *pst;
2721        int cnt;
2722
2723        st = locate_simplify_state(revs, commit);
2724
2725        /*
2726         * Have we handled this one?
2727         */
2728        if (st->simplified)
2729                return tail;
2730
2731        /*
2732         * An UNINTERESTING commit simplifies to itself, so does a
2733         * root commit.  We do not rewrite parents of such commit
2734         * anyway.
2735         */
2736        if ((commit->object.flags & UNINTERESTING) || !commit->parents) {
2737                st->simplified = commit;
2738                return tail;
2739        }
2740
2741        /*
2742         * Do we know what commit all of our parents that matter
2743         * should be rewritten to?  Otherwise we are not ready to
2744         * rewrite this one yet.
2745         */
2746        for (cnt = 0, p = commit->parents; p; p = p->next) {
2747                pst = locate_simplify_state(revs, p->item);
2748                if (!pst->simplified) {
2749                        tail = &commit_list_insert(p->item, tail)->next;
2750                        cnt++;
2751                }
2752                if (revs->first_parent_only)
2753                        break;
2754        }
2755        if (cnt) {
2756                tail = &commit_list_insert(commit, tail)->next;
2757                return tail;
2758        }
2759
2760        /*
2761         * Rewrite our list of parents. Note that this cannot
2762         * affect our TREESAME flags in any way - a commit is
2763         * always TREESAME to its simplification.
2764         */
2765        for (p = commit->parents; p; p = p->next) {
2766                pst = locate_simplify_state(revs, p->item);
2767                p->item = pst->simplified;
2768                if (revs->first_parent_only)
2769                        break;
2770        }
2771
2772        if (revs->first_parent_only)
2773                cnt = 1;
2774        else
2775                cnt = remove_duplicate_parents(revs, commit);
2776
2777        /*
2778         * It is possible that we are a merge and one side branch
2779         * does not have any commit that touches the given paths;
2780         * in such a case, the immediate parent from that branch
2781         * will be rewritten to be the merge base.
2782         *
2783         *      o----X          X: the commit we are looking at;
2784         *     /    /           o: a commit that touches the paths;
2785         * ---o----'
2786         *
2787         * Further, a merge of an independent branch that doesn't
2788         * touch the path will reduce to a treesame root parent:
2789         *
2790         *  ----o----X          X: the commit we are looking at;
2791         *          /           o: a commit that touches the paths;
2792         *         r            r: a root commit not touching the paths
2793         *
2794         * Detect and simplify both cases.
2795         */
2796        if (1 < cnt) {
2797                int marked = mark_redundant_parents(revs, commit);
2798                marked += mark_treesame_root_parents(revs, commit);
2799                if (marked)
2800                        marked -= leave_one_treesame_to_parent(revs, commit);
2801                if (marked)
2802                        cnt = remove_marked_parents(revs, commit);
2803        }
2804
2805        /*
2806         * A commit simplifies to itself if it is a root, if it is
2807         * UNINTERESTING, if it touches the given paths, or if it is a
2808         * merge and its parents don't simplify to one relevant commit
2809         * (the first two cases are already handled at the beginning of
2810         * this function).
2811         *
2812         * Otherwise, it simplifies to what its sole relevant parent
2813         * simplifies to.
2814         */
2815        if (!cnt ||
2816            (commit->object.flags & UNINTERESTING) ||
2817            !(commit->object.flags & TREESAME) ||
2818            (parent = one_relevant_parent(revs, commit->parents)) == NULL)
2819                st->simplified = commit;
2820        else {
2821                pst = locate_simplify_state(revs, parent);
2822                st->simplified = pst->simplified;
2823        }
2824        return tail;
2825}
2826
2827static void simplify_merges(struct rev_info *revs)
2828{
2829        struct commit_list *list, *next;
2830        struct commit_list *yet_to_do, **tail;
2831        struct commit *commit;
2832
2833        if (!revs->prune)
2834                return;
2835
2836        /* feed the list reversed */
2837        yet_to_do = NULL;
2838        for (list = revs->commits; list; list = next) {
2839                commit = list->item;
2840                next = list->next;
2841                /*
2842                 * Do not free(list) here yet; the original list
2843                 * is used later in this function.
2844                 */
2845                commit_list_insert(commit, &yet_to_do);
2846        }
2847        while (yet_to_do) {
2848                list = yet_to_do;
2849                yet_to_do = NULL;
2850                tail = &yet_to_do;
2851                while (list) {
2852                        commit = pop_commit(&list);
2853                        tail = simplify_one(revs, commit, tail);
2854                }
2855        }
2856
2857        /* clean up the result, removing the simplified ones */
2858        list = revs->commits;
2859        revs->commits = NULL;
2860        tail = &revs->commits;
2861        while (list) {
2862                struct merge_simplify_state *st;
2863
2864                commit = pop_commit(&list);
2865                st = locate_simplify_state(revs, commit);
2866                if (st->simplified == commit)
2867                        tail = &commit_list_insert(commit, tail)->next;
2868        }
2869}
2870
2871static void set_children(struct rev_info *revs)
2872{
2873        struct commit_list *l;
2874        for (l = revs->commits; l; l = l->next) {
2875                struct commit *commit = l->item;
2876                struct commit_list *p;
2877
2878                for (p = commit->parents; p; p = p->next)
2879                        add_child(revs, p->item, commit);
2880        }
2881}
2882
2883void reset_revision_walk(void)
2884{
2885        clear_object_flags(SEEN | ADDED | SHOWN);
2886}
2887
2888static int mark_uninteresting(const struct object_id *oid,
2889                              struct packed_git *pack,
2890                              uint32_t pos,
2891                              void *unused)
2892{
2893        struct object *o = parse_object(the_repository, oid);
2894        o->flags |= UNINTERESTING | SEEN;
2895        return 0;
2896}
2897
2898struct topo_walk_info {};
2899
2900static void init_topo_walk(struct rev_info *revs)
2901{
2902        struct topo_walk_info *info;
2903        revs->topo_walk_info = xmalloc(sizeof(struct topo_walk_info));
2904        info = revs->topo_walk_info;
2905        memset(info, 0, sizeof(struct topo_walk_info));
2906
2907        limit_list(revs);
2908        sort_in_topological_order(&revs->commits, revs->sort_order);
2909}
2910
2911static struct commit *next_topo_commit(struct rev_info *revs)
2912{
2913        return pop_commit(&revs->commits);
2914}
2915
2916static void expand_topo_walk(struct rev_info *revs, struct commit *commit)
2917{
2918        if (process_parents(revs, commit, &revs->commits, NULL) < 0) {
2919                if (!revs->ignore_missing_links)
2920                        die("Failed to traverse parents of commit %s",
2921                            oid_to_hex(&commit->object.oid));
2922        }
2923}
2924
2925int prepare_revision_walk(struct rev_info *revs)
2926{
2927        int i;
2928        struct object_array old_pending;
2929        struct commit_list **next = &revs->commits;
2930
2931        memcpy(&old_pending, &revs->pending, sizeof(old_pending));
2932        revs->pending.nr = 0;
2933        revs->pending.alloc = 0;
2934        revs->pending.objects = NULL;
2935        for (i = 0; i < old_pending.nr; i++) {
2936                struct object_array_entry *e = old_pending.objects + i;
2937                struct commit *commit = handle_commit(revs, e);
2938                if (commit) {
2939                        if (!(commit->object.flags & SEEN)) {
2940                                commit->object.flags |= SEEN;
2941                                next = commit_list_append(commit, next);
2942                        }
2943                }
2944        }
2945        object_array_clear(&old_pending);
2946
2947        /* Signal whether we need per-parent treesame decoration */
2948        if (revs->simplify_merges ||
2949            (revs->limited && limiting_can_increase_treesame(revs)))
2950                revs->treesame.name = "treesame";
2951
2952        if (revs->exclude_promisor_objects) {
2953                for_each_packed_object(mark_uninteresting, NULL,
2954                                       FOR_EACH_OBJECT_PROMISOR_ONLY);
2955        }
2956
2957        if (revs->no_walk != REVISION_WALK_NO_WALK_UNSORTED)
2958                commit_list_sort_by_date(&revs->commits);
2959        if (revs->no_walk)
2960                return 0;
2961        if (revs->limited) {
2962                if (limit_list(revs) < 0)
2963                        return -1;
2964                if (revs->topo_order)
2965                        sort_in_topological_order(&revs->commits, revs->sort_order);
2966        } else if (revs->topo_order)
2967                init_topo_walk(revs);
2968        if (revs->line_level_traverse)
2969                line_log_filter(revs);
2970        if (revs->simplify_merges)
2971                simplify_merges(revs);
2972        if (revs->children.name)
2973                set_children(revs);
2974        return 0;
2975}
2976
2977static enum rewrite_result rewrite_one(struct rev_info *revs, struct commit **pp)
2978{
2979        struct commit_list *cache = NULL;
2980
2981        for (;;) {
2982                struct commit *p = *pp;
2983                if (!revs->limited)
2984                        if (process_parents(revs, p, &revs->commits, &cache) < 0)
2985                                return rewrite_one_error;
2986                if (p->object.flags & UNINTERESTING)
2987                        return rewrite_one_ok;
2988                if (!(p->object.flags & TREESAME))
2989                        return rewrite_one_ok;
2990                if (!p->parents)
2991                        return rewrite_one_noparents;
2992                if ((p = one_relevant_parent(revs, p->parents)) == NULL)
2993                        return rewrite_one_ok;
2994                *pp = p;
2995        }
2996}
2997
2998int rewrite_parents(struct rev_info *revs, struct commit *commit,
2999        rewrite_parent_fn_t rewrite_parent)
3000{
3001        struct commit_list **pp = &commit->parents;
3002        while (*pp) {
3003                struct commit_list *parent = *pp;
3004                switch (rewrite_parent(revs, &parent->item)) {
3005                case rewrite_one_ok:
3006                        break;
3007                case rewrite_one_noparents:
3008                        *pp = parent->next;
3009                        continue;
3010                case rewrite_one_error:
3011                        return -1;
3012                }
3013                pp = &parent->next;
3014        }
3015        remove_duplicate_parents(revs, commit);
3016        return 0;
3017}
3018
3019static int commit_rewrite_person(struct strbuf *buf, const char *what, struct string_list *mailmap)
3020{
3021        char *person, *endp;
3022        size_t len, namelen, maillen;
3023        const char *name;
3024        const char *mail;
3025        struct ident_split ident;
3026
3027        person = strstr(buf->buf, what);
3028        if (!person)
3029                return 0;
3030
3031        person += strlen(what);
3032        endp = strchr(person, '\n');
3033        if (!endp)
3034                return 0;
3035
3036        len = endp - person;
3037
3038        if (split_ident_line(&ident, person, len))
3039                return 0;
3040
3041        mail = ident.mail_begin;
3042        maillen = ident.mail_end - ident.mail_begin;
3043        name = ident.name_begin;
3044        namelen = ident.name_end - ident.name_begin;
3045
3046        if (map_user(mailmap, &mail, &maillen, &name, &namelen)) {
3047                struct strbuf namemail = STRBUF_INIT;
3048
3049                strbuf_addf(&namemail, "%.*s <%.*s>",
3050                            (int)namelen, name, (int)maillen, mail);
3051
3052                strbuf_splice(buf, ident.name_begin - buf->buf,
3053                              ident.mail_end - ident.name_begin + 1,
3054                              namemail.buf, namemail.len);
3055
3056                strbuf_release(&namemail);
3057
3058                return 1;
3059        }
3060
3061        return 0;
3062}
3063
3064static int commit_match(struct commit *commit, struct rev_info *opt)
3065{
3066        int retval;
3067        const char *encoding;
3068        const char *message;
3069        struct strbuf buf = STRBUF_INIT;
3070
3071        if (!opt->grep_filter.pattern_list && !opt->grep_filter.header_list)
3072                return 1;
3073
3074        /* Prepend "fake" headers as needed */
3075        if (opt->grep_filter.use_reflog_filter) {
3076                strbuf_addstr(&buf, "reflog ");
3077                get_reflog_message(&buf, opt->reflog_info);
3078                strbuf_addch(&buf, '\n');
3079        }
3080
3081        /*
3082         * We grep in the user's output encoding, under the assumption that it
3083         * is the encoding they are most likely to write their grep pattern
3084         * for. In addition, it means we will match the "notes" encoding below,
3085         * so we will not end up with a buffer that has two different encodings
3086         * in it.
3087         */
3088        encoding = get_log_output_encoding();
3089        message = logmsg_reencode(commit, NULL, encoding);
3090
3091        /* Copy the commit to temporary if we are using "fake" headers */
3092        if (buf.len)
3093                strbuf_addstr(&buf, message);
3094
3095        if (opt->grep_filter.header_list && opt->mailmap) {
3096                if (!buf.len)
3097                        strbuf_addstr(&buf, message);
3098
3099                commit_rewrite_person(&buf, "\nauthor ", opt->mailmap);
3100                commit_rewrite_person(&buf, "\ncommitter ", opt->mailmap);
3101        }
3102
3103        /* Append "fake" message parts as needed */
3104        if (opt->show_notes) {
3105                if (!buf.len)
3106                        strbuf_addstr(&buf, message);
3107                format_display_notes(&commit->object.oid, &buf, encoding, 1);
3108        }
3109
3110        /*
3111         * Find either in the original commit message, or in the temporary.
3112         * Note that we cast away the constness of "message" here. It is
3113         * const because it may come from the cached commit buffer. That's OK,
3114         * because we know that it is modifiable heap memory, and that while
3115         * grep_buffer may modify it for speed, it will restore any
3116         * changes before returning.
3117         */
3118        if (buf.len)
3119                retval = grep_buffer(&opt->grep_filter, buf.buf, buf.len);
3120        else
3121                retval = grep_buffer(&opt->grep_filter,
3122                                     (char *)message, strlen(message));
3123        strbuf_release(&buf);
3124        unuse_commit_buffer(commit, message);
3125        return opt->invert_grep ? !retval : retval;
3126}
3127
3128static inline int want_ancestry(const struct rev_info *revs)
3129{
3130        return (revs->rewrite_parents || revs->children.name);
3131}
3132
3133/*
3134 * Return a timestamp to be used for --since/--until comparisons for this
3135 * commit, based on the revision options.
3136 */
3137static timestamp_t comparison_date(const struct rev_info *revs,
3138                                   struct commit *commit)
3139{
3140        return revs->reflog_info ?
3141                get_reflog_timestamp(revs->reflog_info) :
3142                commit->date;
3143}
3144
3145enum commit_action get_commit_action(struct rev_info *revs, struct commit *commit)
3146{
3147        if (commit->object.flags & SHOWN)
3148                return commit_ignore;
3149        if (revs->unpacked && has_object_pack(&commit->object.oid))
3150                return commit_ignore;
3151        if (commit->object.flags & UNINTERESTING)
3152                return commit_ignore;
3153        if (revs->min_age != -1 &&
3154            comparison_date(revs, commit) > revs->min_age)
3155                        return commit_ignore;
3156        if (revs->min_parents || (revs->max_parents >= 0)) {
3157                int n = commit_list_count(commit->parents);
3158                if ((n < revs->min_parents) ||
3159                    ((revs->max_parents >= 0) && (n > revs->max_parents)))
3160                        return commit_ignore;
3161        }
3162        if (!commit_match(commit, revs))
3163                return commit_ignore;
3164        if (revs->prune && revs->dense) {
3165                /* Commit without changes? */
3166                if (commit->object.flags & TREESAME) {
3167                        int n;
3168                        struct commit_list *p;
3169                        /* drop merges unless we want parenthood */
3170                        if (!want_ancestry(revs))
3171                                return commit_ignore;
3172                        /*
3173                         * If we want ancestry, then need to keep any merges
3174                         * between relevant commits to tie together topology.
3175                         * For consistency with TREESAME and simplification
3176                         * use "relevant" here rather than just INTERESTING,
3177                         * to treat bottom commit(s) as part of the topology.
3178                         */
3179                        for (n = 0, p = commit->parents; p; p = p->next)
3180                                if (relevant_commit(p->item))
3181                                        if (++n >= 2)
3182                                                return commit_show;
3183                        return commit_ignore;
3184                }
3185        }
3186        return commit_show;
3187}
3188
3189define_commit_slab(saved_parents, struct commit_list *);
3190
3191#define EMPTY_PARENT_LIST ((struct commit_list *)-1)
3192
3193/*
3194 * You may only call save_parents() once per commit (this is checked
3195 * for non-root commits).
3196 */
3197static void save_parents(struct rev_info *revs, struct commit *commit)
3198{
3199        struct commit_list **pp;
3200
3201        if (!revs->saved_parents_slab) {
3202                revs->saved_parents_slab = xmalloc(sizeof(struct saved_parents));
3203                init_saved_parents(revs->saved_parents_slab);
3204        }
3205
3206        pp = saved_parents_at(revs->saved_parents_slab, commit);
3207
3208        /*
3209         * When walking with reflogs, we may visit the same commit
3210         * several times: once for each appearance in the reflog.
3211         *
3212         * In this case, save_parents() will be called multiple times.
3213         * We want to keep only the first set of parents.  We need to
3214         * store a sentinel value for an empty (i.e., NULL) parent
3215         * list to distinguish it from a not-yet-saved list, however.
3216         */
3217        if (*pp)
3218                return;
3219        if (commit->parents)
3220                *pp = copy_commit_list(commit->parents);
3221        else
3222                *pp = EMPTY_PARENT_LIST;
3223}
3224
3225static void free_saved_parents(struct rev_info *revs)
3226{
3227        if (revs->saved_parents_slab)
3228                clear_saved_parents(revs->saved_parents_slab);
3229}
3230
3231struct commit_list *get_saved_parents(struct rev_info *revs, const struct commit *commit)
3232{
3233        struct commit_list *parents;
3234
3235        if (!revs->saved_parents_slab)
3236                return commit->parents;
3237
3238        parents = *saved_parents_at(revs->saved_parents_slab, commit);
3239        if (parents == EMPTY_PARENT_LIST)
3240                return NULL;
3241        return parents;
3242}
3243
3244enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit)
3245{
3246        enum commit_action action = get_commit_action(revs, commit);
3247
3248        if (action == commit_show &&
3249            revs->prune && revs->dense && want_ancestry(revs)) {
3250                /*
3251                 * --full-diff on simplified parents is no good: it
3252                 * will show spurious changes from the commits that
3253                 * were elided.  So we save the parents on the side
3254                 * when --full-diff is in effect.
3255                 */
3256                if (revs->full_diff)
3257                        save_parents(revs, commit);
3258                if (rewrite_parents(revs, commit, rewrite_one) < 0)
3259                        return commit_error;
3260        }
3261        return action;
3262}
3263
3264static void track_linear(struct rev_info *revs, struct commit *commit)
3265{
3266        if (revs->track_first_time) {
3267                revs->linear = 1;
3268                revs->track_first_time = 0;
3269        } else {
3270                struct commit_list *p;
3271                for (p = revs->previous_parents; p; p = p->next)
3272                        if (p->item == NULL || /* first commit */
3273                            oideq(&p->item->object.oid, &commit->object.oid))
3274                                break;
3275                revs->linear = p != NULL;
3276        }
3277        if (revs->reverse) {
3278                if (revs->linear)
3279                        commit->object.flags |= TRACK_LINEAR;
3280        }
3281        free_commit_list(revs->previous_parents);
3282        revs->previous_parents = copy_commit_list(commit->parents);
3283}
3284
3285static struct commit *get_revision_1(struct rev_info *revs)
3286{
3287        while (1) {
3288                struct commit *commit;
3289
3290                if (revs->reflog_info)
3291                        commit = next_reflog_entry(revs->reflog_info);
3292                else if (revs->topo_walk_info)
3293                        commit = next_topo_commit(revs);
3294                else
3295                        commit = pop_commit(&revs->commits);
3296
3297                if (!commit)
3298                        return NULL;
3299
3300                if (revs->reflog_info)
3301                        commit->object.flags &= ~(ADDED | SEEN | SHOWN);
3302
3303                /*
3304                 * If we haven't done the list limiting, we need to look at
3305                 * the parents here. We also need to do the date-based limiting
3306                 * that we'd otherwise have done in limit_list().
3307                 */
3308                if (!revs->limited) {
3309                        if (revs->max_age != -1 &&
3310                            comparison_date(revs, commit) < revs->max_age)
3311                                continue;
3312
3313                        if (revs->reflog_info)
3314                                try_to_simplify_commit(revs, commit);
3315                        else if (revs->topo_walk_info)
3316                                expand_topo_walk(revs, commit);
3317                        else if (process_parents(revs, commit, &revs->commits, NULL) < 0) {
3318                                if (!revs->ignore_missing_links)
3319                                        die("Failed to traverse parents of commit %s",
3320                                                oid_to_hex(&commit->object.oid));
3321                        }
3322                }
3323
3324                switch (simplify_commit(revs, commit)) {
3325                case commit_ignore:
3326                        continue;
3327                case commit_error:
3328                        die("Failed to simplify parents of commit %s",
3329                            oid_to_hex(&commit->object.oid));
3330                default:
3331                        if (revs->track_linear)
3332                                track_linear(revs, commit);
3333                        return commit;
3334                }
3335        }
3336}
3337
3338/*
3339 * Return true for entries that have not yet been shown.  (This is an
3340 * object_array_each_func_t.)
3341 */
3342static int entry_unshown(struct object_array_entry *entry, void *cb_data_unused)
3343{
3344        return !(entry->item->flags & SHOWN);
3345}
3346
3347/*
3348 * If array is on the verge of a realloc, garbage-collect any entries
3349 * that have already been shown to try to free up some space.
3350 */
3351static void gc_boundary(struct object_array *array)
3352{
3353        if (array->nr == array->alloc)
3354                object_array_filter(array, entry_unshown, NULL);
3355}
3356
3357static void create_boundary_commit_list(struct rev_info *revs)
3358{
3359        unsigned i;
3360        struct commit *c;
3361        struct object_array *array = &revs->boundary_commits;
3362        struct object_array_entry *objects = array->objects;
3363
3364        /*
3365         * If revs->commits is non-NULL at this point, an error occurred in
3366         * get_revision_1().  Ignore the error and continue printing the
3367         * boundary commits anyway.  (This is what the code has always
3368         * done.)
3369         */
3370        if (revs->commits) {
3371                free_commit_list(revs->commits);
3372                revs->commits = NULL;
3373        }
3374
3375        /*
3376         * Put all of the actual boundary commits from revs->boundary_commits
3377         * into revs->commits
3378         */
3379        for (i = 0; i < array->nr; i++) {
3380                c = (struct commit *)(objects[i].item);
3381                if (!c)
3382                        continue;
3383                if (!(c->object.flags & CHILD_SHOWN))
3384                        continue;
3385                if (c->object.flags & (SHOWN | BOUNDARY))
3386                        continue;
3387                c->object.flags |= BOUNDARY;
3388                commit_list_insert(c, &revs->commits);
3389        }
3390
3391        /*
3392         * If revs->topo_order is set, sort the boundary commits
3393         * in topological order
3394         */
3395        sort_in_topological_order(&revs->commits, revs->sort_order);
3396}
3397
3398static struct commit *get_revision_internal(struct rev_info *revs)
3399{
3400        struct commit *c = NULL;
3401        struct commit_list *l;
3402
3403        if (revs->boundary == 2) {
3404                /*
3405                 * All of the normal commits have already been returned,
3406                 * and we are now returning boundary commits.
3407                 * create_boundary_commit_list() has populated
3408                 * revs->commits with the remaining commits to return.
3409                 */
3410                c = pop_commit(&revs->commits);
3411                if (c)
3412                        c->object.flags |= SHOWN;
3413                return c;
3414        }
3415
3416        /*
3417         * If our max_count counter has reached zero, then we are done. We
3418         * don't simply return NULL because we still might need to show
3419         * boundary commits. But we want to avoid calling get_revision_1, which
3420         * might do a considerable amount of work finding the next commit only
3421         * for us to throw it away.
3422         *
3423         * If it is non-zero, then either we don't have a max_count at all
3424         * (-1), or it is still counting, in which case we decrement.
3425         */
3426        if (revs->max_count) {
3427                c = get_revision_1(revs);
3428                if (c) {
3429                        while (revs->skip_count > 0) {
3430                                revs->skip_count--;
3431                                c = get_revision_1(revs);
3432                                if (!c)
3433                                        break;
3434                        }
3435                }
3436
3437                if (revs->max_count > 0)
3438                        revs->max_count--;
3439        }
3440
3441        if (c)
3442                c->object.flags |= SHOWN;
3443
3444        if (!revs->boundary)
3445                return c;
3446
3447        if (!c) {
3448                /*
3449                 * get_revision_1() runs out the commits, and
3450                 * we are done computing the boundaries.
3451                 * switch to boundary commits output mode.
3452                 */
3453                revs->boundary = 2;
3454
3455                /*
3456                 * Update revs->commits to contain the list of
3457                 * boundary commits.
3458                 */
3459                create_boundary_commit_list(revs);
3460
3461                return get_revision_internal(revs);
3462        }
3463
3464        /*
3465         * boundary commits are the commits that are parents of the
3466         * ones we got from get_revision_1() but they themselves are
3467         * not returned from get_revision_1().  Before returning
3468         * 'c', we need to mark its parents that they could be boundaries.
3469         */
3470
3471        for (l = c->parents; l; l = l->next) {
3472                struct object *p;
3473                p = &(l->item->object);
3474                if (p->flags & (CHILD_SHOWN | SHOWN))
3475                        continue;
3476                p->flags |= CHILD_SHOWN;
3477                gc_boundary(&revs->boundary_commits);
3478                add_object_array(p, NULL, &revs->boundary_commits);
3479        }
3480
3481        return c;
3482}
3483
3484struct commit *get_revision(struct rev_info *revs)
3485{
3486        struct commit *c;
3487        struct commit_list *reversed;
3488
3489        if (revs->reverse) {
3490                reversed = NULL;
3491                while ((c = get_revision_internal(revs)))
3492                        commit_list_insert(c, &reversed);
3493                revs->commits = reversed;
3494                revs->reverse = 0;
3495                revs->reverse_output_stage = 1;
3496        }
3497
3498        if (revs->reverse_output_stage) {
3499                c = pop_commit(&revs->commits);
3500                if (revs->track_linear)
3501                        revs->linear = !!(c && c->object.flags & TRACK_LINEAR);
3502                return c;
3503        }
3504
3505        c = get_revision_internal(revs);
3506        if (c && revs->graph)
3507                graph_update(revs->graph, c);
3508        if (!c) {
3509                free_saved_parents(revs);
3510                if (revs->previous_parents) {
3511                        free_commit_list(revs->previous_parents);
3512                        revs->previous_parents = NULL;
3513                }
3514        }
3515        return c;
3516}
3517
3518char *get_revision_mark(const struct rev_info *revs, const struct commit *commit)
3519{
3520        if (commit->object.flags & BOUNDARY)
3521                return "-";
3522        else if (commit->object.flags & UNINTERESTING)
3523                return "^";
3524        else if (commit->object.flags & PATCHSAME)
3525                return "=";
3526        else if (!revs || revs->left_right) {
3527                if (commit->object.flags & SYMMETRIC_LEFT)
3528                        return "<";
3529                else
3530                        return ">";
3531        } else if (revs->graph)
3532                return "*";
3533        else if (revs->cherry_mark)
3534                return "+";
3535        return "";
3536}
3537
3538void put_revision_mark(const struct rev_info *revs, const struct commit *commit)
3539{
3540        char *mark = get_revision_mark(revs, commit);
3541        if (!strlen(mark))
3542                return;
3543        fputs(mark, stdout);
3544        putchar(' ');
3545}