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