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