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