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