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