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