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