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