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