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