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