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