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