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