t4216: add end to end tests for git log with Bloom filters
[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                         commit->object.flags |= TREESAME;
993                         return;
994
995                 case REV_TREE_NEW:
996                         if (revs->remove_empty_trees &&
997                             rev_same_tree_as_empty(revs, p)) {
998                                 /* We are adding all the specified
999                                  * paths from this parent, so the
1000                                  * history beyond this parent is not
1001                                  * interesting.  Remove its parents
1002                                  * (they are grandparents for us).
1003                                  * IOW, we pretend this parent is a
1004                                  * "root" commit.
1005                                  */
1006                                 if (parse_commit(p) < 0)
1007                                         die("cannot simplify commit %s (invalid %s)",
1008                                             oid_to_hex(&commit->object.oid),
1009                                             oid_to_hex(&p->object.oid));
1010                                 p->parents = NULL;
1011                         }
1012                 /* fallthrough */
1013                 case REV_TREE_OLD:
1014                 case REV_TREE_DIFFERENT:
1015                         if (relevant_commit(p))
1016                                 relevant_change = 1;
1017                         else
1018                                 irrelevant_change = 1;
1019                         continue;
1020                 }
1021                 die("bad tree compare for commit %s", oid_to_hex(&commit->object.oid));
1022         }
1023
1024         /*
1025          * TREESAME is straightforward for single-parent commits. For merge
1026          * commits, it is most useful to define it so that "irrelevant"
1027          * parents cannot make us !TREESAME - if we have any relevant
1028          * parents, then we only consider TREESAMEness with respect to them,
1029          * allowing irrelevant merges from uninteresting branches to be
1030          * simplified away. Only if we have only irrelevant parents do we
1031          * base TREESAME on them. Note that this logic is replicated in
1032          * update_treesame, which should be kept in sync.
1033          */
1034         if (relevant_parents ? !relevant_change : !irrelevant_change)
1035                 commit->object.flags |= TREESAME;
1036 }
1037
1038 static int process_parents(struct rev_info *revs, struct commit *commit,
1039                            struct commit_list **list, struct prio_queue *queue)
1040 {
1041         struct commit_list *parent = commit->parents;
1042         unsigned left_flag;
1043
1044         if (commit->object.flags & ADDED)
1045                 return 0;
1046         commit->object.flags |= ADDED;
1047
1048         if (revs->include_check &&
1049             !revs->include_check(commit, revs->include_check_data))
1050                 return 0;
1051
1052         /*
1053          * If the commit is uninteresting, don't try to
1054          * prune parents - we want the maximal uninteresting
1055          * set.
1056          *
1057          * Normally we haven't parsed the parent
1058          * yet, so we won't have a parent of a parent
1059          * here. However, it may turn out that we've
1060          * reached this commit some other way (where it
1061          * wasn't uninteresting), in which case we need
1062          * to mark its parents recursively too..
1063          */
1064         if (commit->object.flags & UNINTERESTING) {
1065                 while (parent) {
1066                         struct commit *p = parent->item;
1067                         parent = parent->next;
1068                         if (p)
1069                                 p->object.flags |= UNINTERESTING;
1070                         if (parse_commit_gently(p, 1) < 0)
1071                                 continue;
1072                         if (p->parents)
1073                                 mark_parents_uninteresting(p);
1074                         if (p->object.flags & SEEN)
1075                                 continue;
1076                         p->object.flags |= SEEN;
1077                         if (list)
1078                                 commit_list_insert_by_date(p, list);
1079                         if (queue)
1080                                 prio_queue_put(queue, p);
1081                 }
1082                 return 0;
1083         }
1084
1085         /*
1086          * Ok, the commit wasn't uninteresting. Try to
1087          * simplify the commit history and find the parent
1088          * that has no differences in the path set if one exists.
1089          */
1090         try_to_simplify_commit(revs, commit);
1091
1092         if (revs->no_walk)
1093                 return 0;
1094
1095         left_flag = (commit->object.flags & SYMMETRIC_LEFT);
1096
1097         for (parent = commit->parents; parent; parent = parent->next) {
1098                 struct commit *p = parent->item;
1099                 int gently = revs->ignore_missing_links ||
1100                              revs->exclude_promisor_objects;
1101                 if (parse_commit_gently(p, gently) < 0) {
1102                         if (revs->exclude_promisor_objects &&
1103                             is_promisor_object(&p->object.oid)) {
1104                                 if (revs->first_parent_only)
1105                                         break;
1106                                 continue;
1107                         }
1108                         return -1;
1109                 }
1110                 if (revs->sources) {
1111                         char **slot = revision_sources_at(revs->sources, p);
1112
1113                         if (!*slot)
1114                                 *slot = *revision_sources_at(revs->sources, commit);
1115                 }
1116                 p->object.flags |= left_flag;
1117                 if (!(p->object.flags & SEEN)) {
1118                         p->object.flags |= SEEN;
1119                         if (list)
1120                                 commit_list_insert_by_date(p, list);
1121                         if (queue)
1122                                 prio_queue_put(queue, p);
1123                 }
1124                 if (revs->first_parent_only)
1125                         break;
1126         }
1127         return 0;
1128 }
1129
1130 static void cherry_pick_list(struct commit_list *list, struct rev_info *revs)
1131 {
1132         struct commit_list *p;
1133         int left_count = 0, right_count = 0;
1134         int left_first;
1135         struct patch_ids ids;
1136         unsigned cherry_flag;
1137
1138         /* First count the commits on the left and on the right */
1139         for (p = list; p; p = p->next) {
1140                 struct commit *commit = p->item;
1141                 unsigned flags = commit->object.flags;
1142                 if (flags & BOUNDARY)
1143                         ;
1144                 else if (flags & SYMMETRIC_LEFT)
1145                         left_count++;
1146                 else
1147                         right_count++;
1148         }
1149
1150         if (!left_count || !right_count)
1151                 return;
1152
1153         left_first = left_count < right_count;
1154         init_patch_ids(revs->repo, &ids);
1155         ids.diffopts.pathspec = revs->diffopt.pathspec;
1156
1157         /* Compute patch-ids for one side */
1158         for (p = list; p; p = p->next) {
1159                 struct commit *commit = p->item;
1160                 unsigned flags = commit->object.flags;
1161
1162                 if (flags & BOUNDARY)
1163                         continue;
1164                 /*
1165                  * If we have fewer left, left_first is set and we omit
1166                  * commits on the right branch in this loop.  If we have
1167                  * fewer right, we skip the left ones.
1168                  */
1169                 if (left_first != !!(flags & SYMMETRIC_LEFT))
1170                         continue;
1171                 add_commit_patch_id(commit, &ids);
1172         }
1173
1174         /* either cherry_mark or cherry_pick are true */
1175         cherry_flag = revs->cherry_mark ? PATCHSAME : SHOWN;
1176
1177         /* Check the other side */
1178         for (p = list; p; p = p->next) {
1179                 struct commit *commit = p->item;
1180                 struct patch_id *id;
1181                 unsigned flags = commit->object.flags;
1182
1183                 if (flags & BOUNDARY)
1184                         continue;
1185                 /*
1186                  * If we have fewer left, left_first is set and we omit
1187                  * commits on the left branch in this loop.
1188                  */
1189                 if (left_first == !!(flags & SYMMETRIC_LEFT))
1190                         continue;
1191
1192                 /*
1193                  * Have we seen the same patch id?
1194                  */
1195                 id = has_commit_patch_id(commit, &ids);
1196                 if (!id)
1197                         continue;
1198
1199                 commit->object.flags |= cherry_flag;
1200                 id->commit->object.flags |= cherry_flag;
1201         }
1202
1203         free_patch_ids(&ids);
1204 }
1205
1206 /* How many extra uninteresting commits we want to see.. */
1207 #define SLOP 5
1208
1209 static int still_interesting(struct commit_list *src, timestamp_t date, int slop,
1210                              struct commit **interesting_cache)
1211 {
1212         /*
1213          * No source list at all? We're definitely done..
1214          */
1215         if (!src)
1216                 return 0;
1217
1218         /*
1219          * Does the destination list contain entries with a date
1220          * before the source list? Definitely _not_ done.
1221          */
1222         if (date <= src->item->date)
1223                 return SLOP;
1224
1225         /*
1226          * Does the source list still have interesting commits in
1227          * it? Definitely not done..
1228          */
1229         if (!everybody_uninteresting(src, interesting_cache))
1230                 return SLOP;
1231
1232         /* Ok, we're closing in.. */
1233         return slop-1;
1234 }
1235
1236 /*
1237  * "rev-list --ancestry-path A..B" computes commits that are ancestors
1238  * of B but not ancestors of A but further limits the result to those
1239  * that are descendants of A.  This takes the list of bottom commits and
1240  * the result of "A..B" without --ancestry-path, and limits the latter
1241  * further to the ones that can reach one of the commits in "bottom".
1242  */
1243 static void limit_to_ancestry(struct commit_list *bottom, struct commit_list *list)
1244 {
1245         struct commit_list *p;
1246         struct commit_list *rlist = NULL;
1247         int made_progress;
1248
1249         /*
1250          * Reverse the list so that it will be likely that we would
1251          * process parents before children.
1252          */
1253         for (p = list; p; p = p->next)
1254                 commit_list_insert(p->item, &rlist);
1255
1256         for (p = bottom; p; p = p->next)
1257                 p->item->object.flags |= TMP_MARK;
1258
1259         /*
1260          * Mark the ones that can reach bottom commits in "list",
1261          * in a bottom-up fashion.
1262          */
1263         do {
1264                 made_progress = 0;
1265                 for (p = rlist; p; p = p->next) {
1266                         struct commit *c = p->item;
1267                         struct commit_list *parents;
1268                         if (c->object.flags & (TMP_MARK | UNINTERESTING))
1269                                 continue;
1270                         for (parents = c->parents;
1271                              parents;
1272                              parents = parents->next) {
1273                                 if (!(parents->item->object.flags & TMP_MARK))
1274                                         continue;
1275                                 c->object.flags |= TMP_MARK;
1276                                 made_progress = 1;
1277                                 break;
1278                         }
1279                 }
1280         } while (made_progress);
1281
1282         /*
1283          * NEEDSWORK: decide if we want to remove parents that are
1284          * not marked with TMP_MARK from commit->parents for commits
1285          * in the resulting list.  We may not want to do that, though.
1286          */
1287
1288         /*
1289          * The ones that are not marked with TMP_MARK are uninteresting
1290          */
1291         for (p = list; p; p = p->next) {
1292                 struct commit *c = p->item;
1293                 if (c->object.flags & TMP_MARK)
1294                         continue;
1295                 c->object.flags |= UNINTERESTING;
1296         }
1297
1298         /* We are done with the TMP_MARK */
1299         for (p = list; p; p = p->next)
1300                 p->item->object.flags &= ~TMP_MARK;
1301         for (p = bottom; p; p = p->next)
1302                 p->item->object.flags &= ~TMP_MARK;
1303         free_commit_list(rlist);
1304 }
1305
1306 /*
1307  * Before walking the history, keep the set of "negative" refs the
1308  * caller has asked to exclude.
1309  *
1310  * This is used to compute "rev-list --ancestry-path A..B", as we need
1311  * to filter the result of "A..B" further to the ones that can actually
1312  * reach A.
1313  */
1314 static struct commit_list *collect_bottom_commits(struct commit_list *list)
1315 {
1316         struct commit_list *elem, *bottom = NULL;
1317         for (elem = list; elem; elem = elem->next)
1318                 if (elem->item->object.flags & BOTTOM)
1319                         commit_list_insert(elem->item, &bottom);
1320         return bottom;
1321 }
1322
1323 /* Assumes either left_only or right_only is set */
1324 static void limit_left_right(struct commit_list *list, struct rev_info *revs)
1325 {
1326         struct commit_list *p;
1327
1328         for (p = list; p; p = p->next) {
1329                 struct commit *commit = p->item;
1330
1331                 if (revs->right_only) {
1332                         if (commit->object.flags & SYMMETRIC_LEFT)
1333                                 commit->object.flags |= SHOWN;
1334                 } else  /* revs->left_only is set */
1335                         if (!(commit->object.flags & SYMMETRIC_LEFT))
1336                                 commit->object.flags |= SHOWN;
1337         }
1338 }
1339
1340 static int limit_list(struct rev_info *revs)
1341 {
1342         int slop = SLOP;
1343         timestamp_t date = TIME_MAX;
1344         struct commit_list *list = revs->commits;
1345         struct commit_list *newlist = NULL;
1346         struct commit_list **p = &newlist;
1347         struct commit_list *bottom = NULL;
1348         struct commit *interesting_cache = NULL;
1349
1350         if (revs->ancestry_path) {
1351                 bottom = collect_bottom_commits(list);
1352                 if (!bottom)
1353                         die("--ancestry-path given but there are no bottom commits");
1354         }
1355
1356         while (list) {
1357                 struct commit *commit = pop_commit(&list);
1358                 struct object *obj = &commit->object;
1359                 show_early_output_fn_t show;
1360
1361                 if (commit == interesting_cache)
1362                         interesting_cache = NULL;
1363
1364                 if (revs->max_age != -1 && (commit->date < revs->max_age))
1365                         obj->flags |= UNINTERESTING;
1366                 if (process_parents(revs, commit, &list, NULL) < 0)
1367                         return -1;
1368                 if (obj->flags & UNINTERESTING) {
1369                         mark_parents_uninteresting(commit);
1370                         slop = still_interesting(list, date, slop, &interesting_cache);
1371                         if (slop)
1372                                 continue;
1373                         break;
1374                 }
1375                 if (revs->min_age != -1 && (commit->date > revs->min_age))
1376                         continue;
1377                 date = commit->date;
1378                 p = &commit_list_insert(commit, p)->next;
1379
1380                 show = show_early_output;
1381                 if (!show)
1382                         continue;
1383
1384                 show(revs, newlist);
1385                 show_early_output = NULL;
1386         }
1387         if (revs->cherry_pick || revs->cherry_mark)
1388                 cherry_pick_list(newlist, revs);
1389
1390         if (revs->left_only || revs->right_only)
1391                 limit_left_right(newlist, revs);
1392
1393         if (bottom) {
1394                 limit_to_ancestry(bottom, newlist);
1395                 free_commit_list(bottom);
1396         }
1397
1398         /*
1399          * Check if any commits have become TREESAME by some of their parents
1400          * becoming UNINTERESTING.
1401          */
1402         if (limiting_can_increase_treesame(revs))
1403                 for (list = newlist; list; list = list->next) {
1404                         struct commit *c = list->item;
1405                         if (c->object.flags & (UNINTERESTING | TREESAME))
1406                                 continue;
1407                         update_treesame(revs, c);
1408                 }
1409
1410         revs->commits = newlist;
1411         return 0;
1412 }
1413
1414 /*
1415  * Add an entry to refs->cmdline with the specified information.
1416  * *name is copied.
1417  */
1418 static void add_rev_cmdline(struct rev_info *revs,
1419                             struct object *item,
1420                             const char *name,
1421                             int whence,
1422                             unsigned flags)
1423 {
1424         struct rev_cmdline_info *info = &revs->cmdline;
1425         unsigned int nr = info->nr;
1426
1427         ALLOC_GROW(info->rev, nr + 1, info->alloc);
1428         info->rev[nr].item = item;
1429         info->rev[nr].name = xstrdup(name);
1430         info->rev[nr].whence = whence;
1431         info->rev[nr].flags = flags;
1432         info->nr++;
1433 }
1434
1435 static void add_rev_cmdline_list(struct rev_info *revs,
1436                                  struct commit_list *commit_list,
1437                                  int whence,
1438                                  unsigned flags)
1439 {
1440         while (commit_list) {
1441                 struct object *object = &commit_list->item->object;
1442                 add_rev_cmdline(revs, object, oid_to_hex(&object->oid),
1443                                 whence, flags);
1444                 commit_list = commit_list->next;
1445         }
1446 }
1447
1448 struct all_refs_cb {
1449         int all_flags;
1450         int warned_bad_reflog;
1451         struct rev_info *all_revs;
1452         const char *name_for_errormsg;
1453         struct worktree *wt;
1454 };
1455
1456 int ref_excluded(struct string_list *ref_excludes, const char *path)
1457 {
1458         struct string_list_item *item;
1459
1460         if (!ref_excludes)
1461                 return 0;
1462         for_each_string_list_item(item, ref_excludes) {
1463                 if (!wildmatch(item->string, path, 0))
1464                         return 1;
1465         }
1466         return 0;
1467 }
1468
1469 static int handle_one_ref(const char *path, const struct object_id *oid,
1470                           int flag, void *cb_data)
1471 {
1472         struct all_refs_cb *cb = cb_data;
1473         struct object *object;
1474
1475         if (ref_excluded(cb->all_revs->ref_excludes, path))
1476             return 0;
1477
1478         object = get_reference(cb->all_revs, path, oid, cb->all_flags);
1479         add_rev_cmdline(cb->all_revs, object, path, REV_CMD_REF, cb->all_flags);
1480         add_pending_oid(cb->all_revs, path, oid, cb->all_flags);
1481         return 0;
1482 }
1483
1484 static void init_all_refs_cb(struct all_refs_cb *cb, struct rev_info *revs,
1485         unsigned flags)
1486 {
1487         cb->all_revs = revs;
1488         cb->all_flags = flags;
1489         revs->rev_input_given = 1;
1490         cb->wt = NULL;
1491 }
1492
1493 void clear_ref_exclusion(struct string_list **ref_excludes_p)
1494 {
1495         if (*ref_excludes_p) {
1496                 string_list_clear(*ref_excludes_p, 0);
1497                 free(*ref_excludes_p);
1498         }
1499         *ref_excludes_p = NULL;
1500 }
1501
1502 void add_ref_exclusion(struct string_list **ref_excludes_p, const char *exclude)
1503 {
1504         if (!*ref_excludes_p) {
1505                 *ref_excludes_p = xcalloc(1, sizeof(**ref_excludes_p));
1506                 (*ref_excludes_p)->strdup_strings = 1;
1507         }
1508         string_list_append(*ref_excludes_p, exclude);
1509 }
1510
1511 static void handle_refs(struct ref_store *refs,
1512                         struct rev_info *revs, unsigned flags,
1513                         int (*for_each)(struct ref_store *, each_ref_fn, void *))
1514 {
1515         struct all_refs_cb cb;
1516
1517         if (!refs) {
1518                 /* this could happen with uninitialized submodules */
1519                 return;
1520         }
1521
1522         init_all_refs_cb(&cb, revs, flags);
1523         for_each(refs, handle_one_ref, &cb);
1524 }
1525
1526 static void handle_one_reflog_commit(struct object_id *oid, void *cb_data)
1527 {
1528         struct all_refs_cb *cb = cb_data;
1529         if (!is_null_oid(oid)) {
1530                 struct object *o = parse_object(cb->all_revs->repo, oid);
1531                 if (o) {
1532                         o->flags |= cb->all_flags;
1533                         /* ??? CMDLINEFLAGS ??? */
1534                         add_pending_object(cb->all_revs, o, "");
1535                 }
1536                 else if (!cb->warned_bad_reflog) {
1537                         warning("reflog of '%s' references pruned commits",
1538                                 cb->name_for_errormsg);
1539                         cb->warned_bad_reflog = 1;
1540                 }
1541         }
1542 }
1543
1544 static int handle_one_reflog_ent(struct object_id *ooid, struct object_id *noid,
1545                 const char *email, timestamp_t timestamp, int tz,
1546                 const char *message, void *cb_data)
1547 {
1548         handle_one_reflog_commit(ooid, cb_data);
1549         handle_one_reflog_commit(noid, cb_data);
1550         return 0;
1551 }
1552
1553 static int handle_one_reflog(const char *refname_in_wt,
1554                              const struct object_id *oid,
1555                              int flag, void *cb_data)
1556 {
1557         struct all_refs_cb *cb = cb_data;
1558         struct strbuf refname = STRBUF_INIT;
1559
1560         cb->warned_bad_reflog = 0;
1561         strbuf_worktree_ref(cb->wt, &refname, refname_in_wt);
1562         cb->name_for_errormsg = refname.buf;
1563         refs_for_each_reflog_ent(get_main_ref_store(the_repository),
1564                                  refname.buf,
1565                                  handle_one_reflog_ent, cb_data);
1566         strbuf_release(&refname);
1567         return 0;
1568 }
1569
1570 static void add_other_reflogs_to_pending(struct all_refs_cb *cb)
1571 {
1572         struct worktree **worktrees, **p;
1573
1574         worktrees = get_worktrees(0);
1575         for (p = worktrees; *p; p++) {
1576                 struct worktree *wt = *p;
1577
1578                 if (wt->is_current)
1579                         continue;
1580
1581                 cb->wt = wt;
1582                 refs_for_each_reflog(get_worktree_ref_store(wt),
1583                                      handle_one_reflog,
1584                                      cb);
1585         }
1586         free_worktrees(worktrees);
1587 }
1588
1589 void add_reflogs_to_pending(struct rev_info *revs, unsigned flags)
1590 {
1591         struct all_refs_cb cb;
1592
1593         cb.all_revs = revs;
1594         cb.all_flags = flags;
1595         cb.wt = NULL;
1596         for_each_reflog(handle_one_reflog, &cb);
1597
1598         if (!revs->single_worktree)
1599                 add_other_reflogs_to_pending(&cb);
1600 }
1601
1602 static void add_cache_tree(struct cache_tree *it, struct rev_info *revs,
1603                            struct strbuf *path, unsigned int flags)
1604 {
1605         size_t baselen = path->len;
1606         int i;
1607
1608         if (it->entry_count >= 0) {
1609                 struct tree *tree = lookup_tree(revs->repo, &it->oid);
1610                 tree->object.flags |= flags;
1611                 add_pending_object_with_path(revs, &tree->object, "",
1612                                              040000, path->buf);
1613         }
1614
1615         for (i = 0; i < it->subtree_nr; i++) {
1616                 struct cache_tree_sub *sub = it->down[i];
1617                 strbuf_addf(path, "%s%s", baselen ? "/" : "", sub->name);
1618                 add_cache_tree(sub->cache_tree, revs, path, flags);
1619                 strbuf_setlen(path, baselen);
1620         }
1621
1622 }
1623
1624 static void do_add_index_objects_to_pending(struct rev_info *revs,
1625                                             struct index_state *istate,
1626                                             unsigned int flags)
1627 {
1628         int i;
1629
1630         for (i = 0; i < istate->cache_nr; i++) {
1631                 struct cache_entry *ce = istate->cache[i];
1632                 struct blob *blob;
1633
1634                 if (S_ISGITLINK(ce->ce_mode))
1635                         continue;
1636
1637                 blob = lookup_blob(revs->repo, &ce->oid);
1638                 if (!blob)
1639                         die("unable to add index blob to traversal");
1640                 blob->object.flags |= flags;
1641                 add_pending_object_with_path(revs, &blob->object, "",
1642                                              ce->ce_mode, ce->name);
1643         }
1644
1645         if (istate->cache_tree) {
1646                 struct strbuf path = STRBUF_INIT;
1647                 add_cache_tree(istate->cache_tree, revs, &path, flags);
1648                 strbuf_release(&path);
1649         }
1650 }
1651
1652 void add_index_objects_to_pending(struct rev_info *revs, unsigned int flags)
1653 {
1654         struct worktree **worktrees, **p;
1655
1656         repo_read_index(revs->repo);
1657         do_add_index_objects_to_pending(revs, revs->repo->index, flags);
1658
1659         if (revs->single_worktree)
1660                 return;
1661
1662         worktrees = get_worktrees(0);
1663         for (p = worktrees; *p; p++) {
1664                 struct worktree *wt = *p;
1665                 struct index_state istate = { NULL };
1666
1667                 if (wt->is_current)
1668                         continue; /* current index already taken care of */
1669
1670                 if (read_index_from(&istate,
1671                                     worktree_git_path(wt, "index"),
1672                                     get_worktree_git_dir(wt)) > 0)
1673                         do_add_index_objects_to_pending(revs, &istate, flags);
1674                 discard_index(&istate);
1675         }
1676         free_worktrees(worktrees);
1677 }
1678
1679 struct add_alternate_refs_data {
1680         struct rev_info *revs;
1681         unsigned int flags;
1682 };
1683
1684 static void add_one_alternate_ref(const struct object_id *oid,
1685                                   void *vdata)
1686 {
1687         const char *name = ".alternate";
1688         struct add_alternate_refs_data *data = vdata;
1689         struct object *obj;
1690
1691         obj = get_reference(data->revs, name, oid, data->flags);
1692         add_rev_cmdline(data->revs, obj, name, REV_CMD_REV, data->flags);
1693         add_pending_object(data->revs, obj, name);
1694 }
1695
1696 static void add_alternate_refs_to_pending(struct rev_info *revs,
1697                                           unsigned int flags)
1698 {
1699         struct add_alternate_refs_data data;
1700         data.revs = revs;
1701         data.flags = flags;
1702         for_each_alternate_ref(add_one_alternate_ref, &data);
1703 }
1704
1705 static int add_parents_only(struct rev_info *revs, const char *arg_, int flags,
1706                             int exclude_parent)
1707 {
1708         struct object_id oid;
1709         struct object *it;
1710         struct commit *commit;
1711         struct commit_list *parents;
1712         int parent_number;
1713         const char *arg = arg_;
1714
1715         if (*arg == '^') {
1716                 flags ^= UNINTERESTING | BOTTOM;
1717                 arg++;
1718         }
1719         if (get_oid_committish(arg, &oid))
1720                 return 0;
1721         while (1) {
1722                 it = get_reference(revs, arg, &oid, 0);
1723                 if (!it && revs->ignore_missing)
1724                         return 0;
1725                 if (it->type != OBJ_TAG)
1726                         break;
1727                 if (!((struct tag*)it)->tagged)
1728                         return 0;
1729                 oidcpy(&oid, &((struct tag*)it)->tagged->oid);
1730         }
1731         if (it->type != OBJ_COMMIT)
1732                 return 0;
1733         commit = (struct commit *)it;
1734         if (exclude_parent &&
1735             exclude_parent > commit_list_count(commit->parents))
1736                 return 0;
1737         for (parents = commit->parents, parent_number = 1;
1738              parents;
1739              parents = parents->next, parent_number++) {
1740                 if (exclude_parent && parent_number != exclude_parent)
1741                         continue;
1742
1743                 it = &parents->item->object;
1744                 it->flags |= flags;
1745                 add_rev_cmdline(revs, it, arg_, REV_CMD_PARENTS_ONLY, flags);
1746                 add_pending_object(revs, it, arg);
1747         }
1748         return 1;
1749 }
1750
1751 void repo_init_revisions(struct repository *r,
1752                          struct rev_info *revs,
1753                          const char *prefix)
1754 {
1755         memset(revs, 0, sizeof(*revs));
1756
1757         revs->repo = r;
1758         revs->abbrev = DEFAULT_ABBREV;
1759         revs->ignore_merges = 1;
1760         revs->simplify_history = 1;
1761         revs->pruning.repo = r;
1762         revs->pruning.flags.recursive = 1;
1763         revs->pruning.flags.quick = 1;
1764         revs->pruning.add_remove = file_add_remove;
1765         revs->pruning.change = file_change;
1766         revs->pruning.change_fn_data = revs;
1767         revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
1768         revs->dense = 1;
1769         revs->prefix = prefix;
1770         revs->max_age = -1;
1771         revs->min_age = -1;
1772         revs->skip_count = -1;
1773         revs->max_count = -1;
1774         revs->max_parents = -1;
1775         revs->expand_tabs_in_log = -1;
1776
1777         revs->commit_format = CMIT_FMT_DEFAULT;
1778         revs->expand_tabs_in_log_default = 8;
1779
1780         init_grep_defaults(revs->repo);
1781         grep_init(&revs->grep_filter, revs->repo, prefix);
1782         revs->grep_filter.status_only = 1;
1783
1784         repo_diff_setup(revs->repo, &revs->diffopt);
1785         if (prefix && !revs->diffopt.prefix) {
1786                 revs->diffopt.prefix = prefix;
1787                 revs->diffopt.prefix_length = strlen(prefix);
1788         }
1789
1790         init_display_notes(&revs->notes_opt);
1791 }
1792
1793 static void add_pending_commit_list(struct rev_info *revs,
1794                                     struct commit_list *commit_list,
1795                                     unsigned int flags)
1796 {
1797         while (commit_list) {
1798                 struct object *object = &commit_list->item->object;
1799                 object->flags |= flags;
1800                 add_pending_object(revs, object, oid_to_hex(&object->oid));
1801                 commit_list = commit_list->next;
1802         }
1803 }
1804
1805 static void prepare_show_merge(struct rev_info *revs)
1806 {
1807         struct commit_list *bases;
1808         struct commit *head, *other;
1809         struct object_id oid;
1810         const char **prune = NULL;
1811         int i, prune_num = 1; /* counting terminating NULL */
1812         struct index_state *istate = revs->repo->index;
1813
1814         if (get_oid("HEAD", &oid))
1815                 die("--merge without HEAD?");
1816         head = lookup_commit_or_die(&oid, "HEAD");
1817         if (get_oid("MERGE_HEAD", &oid))
1818                 die("--merge without MERGE_HEAD?");
1819         other = lookup_commit_or_die(&oid, "MERGE_HEAD");
1820         add_pending_object(revs, &head->object, "HEAD");
1821         add_pending_object(revs, &other->object, "MERGE_HEAD");
1822         bases = get_merge_bases(head, other);
1823         add_rev_cmdline_list(revs, bases, REV_CMD_MERGE_BASE, UNINTERESTING | BOTTOM);
1824         add_pending_commit_list(revs, bases, UNINTERESTING | BOTTOM);
1825         free_commit_list(bases);
1826         head->object.flags |= SYMMETRIC_LEFT;
1827
1828         if (!istate->cache_nr)
1829                 repo_read_index(revs->repo);
1830         for (i = 0; i < istate->cache_nr; i++) {
1831                 const struct cache_entry *ce = istate->cache[i];
1832                 if (!ce_stage(ce))
1833                         continue;
1834                 if (ce_path_match(istate, ce, &revs->prune_data, NULL)) {
1835                         prune_num++;
1836                         REALLOC_ARRAY(prune, prune_num);
1837                         prune[prune_num-2] = ce->name;
1838                         prune[prune_num-1] = NULL;
1839                 }
1840                 while ((i+1 < istate->cache_nr) &&
1841                        ce_same_name(ce, istate->cache[i+1]))
1842                         i++;
1843         }
1844         clear_pathspec(&revs->prune_data);
1845         parse_pathspec(&revs->prune_data, PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1846                        PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH, "", prune);
1847         revs->limited = 1;
1848 }
1849
1850 static int dotdot_missing(const char *arg, char *dotdot,
1851                           struct rev_info *revs, int symmetric)
1852 {
1853         if (revs->ignore_missing)
1854                 return 0;
1855         /* de-munge so we report the full argument */
1856         *dotdot = '.';
1857         die(symmetric
1858             ? "Invalid symmetric difference expression %s"
1859             : "Invalid revision range %s", arg);
1860 }
1861
1862 static int handle_dotdot_1(const char *arg, char *dotdot,
1863                            struct rev_info *revs, int flags,
1864                            int cant_be_filename,
1865                            struct object_context *a_oc,
1866                            struct object_context *b_oc)
1867 {
1868         const char *a_name, *b_name;
1869         struct object_id a_oid, b_oid;
1870         struct object *a_obj, *b_obj;
1871         unsigned int a_flags, b_flags;
1872         int symmetric = 0;
1873         unsigned int flags_exclude = flags ^ (UNINTERESTING | BOTTOM);
1874         unsigned int oc_flags = GET_OID_COMMITTISH | GET_OID_RECORD_PATH;
1875
1876         a_name = arg;
1877         if (!*a_name)
1878                 a_name = "HEAD";
1879
1880         b_name = dotdot + 2;
1881         if (*b_name == '.') {
1882                 symmetric = 1;
1883                 b_name++;
1884         }
1885         if (!*b_name)
1886                 b_name = "HEAD";
1887
1888         if (get_oid_with_context(revs->repo, a_name, oc_flags, &a_oid, a_oc) ||
1889             get_oid_with_context(revs->repo, b_name, oc_flags, &b_oid, b_oc))
1890                 return -1;
1891
1892         if (!cant_be_filename) {
1893                 *dotdot = '.';
1894                 verify_non_filename(revs->prefix, arg);
1895                 *dotdot = '\0';
1896         }
1897
1898         a_obj = parse_object(revs->repo, &a_oid);
1899         b_obj = parse_object(revs->repo, &b_oid);
1900         if (!a_obj || !b_obj)
1901                 return dotdot_missing(arg, dotdot, revs, symmetric);
1902
1903         if (!symmetric) {
1904                 /* just A..B */
1905                 b_flags = flags;
1906                 a_flags = flags_exclude;
1907         } else {
1908                 /* A...B -- find merge bases between the two */
1909                 struct commit *a, *b;
1910                 struct commit_list *exclude;
1911
1912                 a = lookup_commit_reference(revs->repo, &a_obj->oid);
1913                 b = lookup_commit_reference(revs->repo, &b_obj->oid);
1914                 if (!a || !b)
1915                         return dotdot_missing(arg, dotdot, revs, symmetric);
1916
1917                 exclude = get_merge_bases(a, b);
1918                 add_rev_cmdline_list(revs, exclude, REV_CMD_MERGE_BASE,
1919                                      flags_exclude);
1920                 add_pending_commit_list(revs, exclude, flags_exclude);
1921                 free_commit_list(exclude);
1922
1923                 b_flags = flags;
1924                 a_flags = flags | SYMMETRIC_LEFT;
1925         }
1926
1927         a_obj->flags |= a_flags;
1928         b_obj->flags |= b_flags;
1929         add_rev_cmdline(revs, a_obj, a_name, REV_CMD_LEFT, a_flags);
1930         add_rev_cmdline(revs, b_obj, b_name, REV_CMD_RIGHT, b_flags);
1931         add_pending_object_with_path(revs, a_obj, a_name, a_oc->mode, a_oc->path);
1932         add_pending_object_with_path(revs, b_obj, b_name, b_oc->mode, b_oc->path);
1933         return 0;
1934 }
1935
1936 static int handle_dotdot(const char *arg,
1937                          struct rev_info *revs, int flags,
1938                          int cant_be_filename)
1939 {
1940         struct object_context a_oc, b_oc;
1941         char *dotdot = strstr(arg, "..");
1942         int ret;
1943
1944         if (!dotdot)
1945                 return -1;
1946
1947         memset(&a_oc, 0, sizeof(a_oc));
1948         memset(&b_oc, 0, sizeof(b_oc));
1949
1950         *dotdot = '\0';
1951         ret = handle_dotdot_1(arg, dotdot, revs, flags, cant_be_filename,
1952                               &a_oc, &b_oc);
1953         *dotdot = '.';
1954
1955         free(a_oc.path);
1956         free(b_oc.path);
1957
1958         return ret;
1959 }
1960
1961 int handle_revision_arg(const char *arg_, struct rev_info *revs, int flags, unsigned revarg_opt)
1962 {
1963         struct object_context oc;
1964         char *mark;
1965         struct object *object;
1966         struct object_id oid;
1967         int local_flags;
1968         const char *arg = arg_;
1969         int cant_be_filename = revarg_opt & REVARG_CANNOT_BE_FILENAME;
1970         unsigned get_sha1_flags = GET_OID_RECORD_PATH;
1971
1972         flags = flags & UNINTERESTING ? flags | BOTTOM : flags & ~BOTTOM;
1973
1974         if (!cant_be_filename && !strcmp(arg, "..")) {
1975                 /*
1976                  * Just ".."?  That is not a range but the
1977                  * pathspec for the parent directory.
1978                  */
1979                 return -1;
1980         }
1981
1982         if (!handle_dotdot(arg, revs, flags, revarg_opt))
1983                 return 0;
1984
1985         mark = strstr(arg, "^@");
1986         if (mark && !mark[2]) {
1987                 *mark = 0;
1988                 if (add_parents_only(revs, arg, flags, 0))
1989                         return 0;
1990                 *mark = '^';
1991         }
1992         mark = strstr(arg, "^!");
1993         if (mark && !mark[2]) {
1994                 *mark = 0;
1995                 if (!add_parents_only(revs, arg, flags ^ (UNINTERESTING | BOTTOM), 0))
1996                         *mark = '^';
1997         }
1998         mark = strstr(arg, "^-");
1999         if (mark) {
2000                 int exclude_parent = 1;
2001
2002                 if (mark[2]) {
2003                         char *end;
2004                         exclude_parent = strtoul(mark + 2, &end, 10);
2005                         if (*end != '\0' || !exclude_parent)
2006                                 return -1;
2007                 }
2008
2009                 *mark = 0;
2010                 if (!add_parents_only(revs, arg, flags ^ (UNINTERESTING | BOTTOM), exclude_parent))
2011                         *mark = '^';
2012         }
2013
2014         local_flags = 0;
2015         if (*arg == '^') {
2016                 local_flags = UNINTERESTING | BOTTOM;
2017                 arg++;
2018         }
2019
2020         if (revarg_opt & REVARG_COMMITTISH)
2021                 get_sha1_flags |= GET_OID_COMMITTISH;
2022
2023         if (get_oid_with_context(revs->repo, arg, get_sha1_flags, &oid, &oc))
2024                 return revs->ignore_missing ? 0 : -1;
2025         if (!cant_be_filename)
2026                 verify_non_filename(revs->prefix, arg);
2027         object = get_reference(revs, arg, &oid, flags ^ local_flags);
2028         if (!object)
2029                 return revs->ignore_missing ? 0 : -1;
2030         add_rev_cmdline(revs, object, arg_, REV_CMD_REV, flags ^ local_flags);
2031         add_pending_object_with_path(revs, object, arg, oc.mode, oc.path);
2032         free(oc.path);
2033         return 0;
2034 }
2035
2036 static void read_pathspec_from_stdin(struct strbuf *sb,
2037                                      struct argv_array *prune)
2038 {
2039         while (strbuf_getline(sb, stdin) != EOF)
2040                 argv_array_push(prune, sb->buf);
2041 }
2042
2043 static void read_revisions_from_stdin(struct rev_info *revs,
2044                                       struct argv_array *prune)
2045 {
2046         struct strbuf sb;
2047         int seen_dashdash = 0;
2048         int save_warning;
2049
2050         save_warning = warn_on_object_refname_ambiguity;
2051         warn_on_object_refname_ambiguity = 0;
2052
2053         strbuf_init(&sb, 1000);
2054         while (strbuf_getline(&sb, stdin) != EOF) {
2055                 int len = sb.len;
2056                 if (!len)
2057                         break;
2058                 if (sb.buf[0] == '-') {
2059                         if (len == 2 && sb.buf[1] == '-') {
2060                                 seen_dashdash = 1;
2061                                 break;
2062                         }
2063                         die("options not supported in --stdin mode");
2064                 }
2065                 if (handle_revision_arg(sb.buf, revs, 0,
2066                                         REVARG_CANNOT_BE_FILENAME))
2067                         die("bad revision '%s'", sb.buf);
2068         }
2069         if (seen_dashdash)
2070                 read_pathspec_from_stdin(&sb, prune);
2071
2072         strbuf_release(&sb);
2073         warn_on_object_refname_ambiguity = save_warning;
2074 }
2075
2076 static void add_grep(struct rev_info *revs, const char *ptn, enum grep_pat_token what)
2077 {
2078         append_grep_pattern(&revs->grep_filter, ptn, "command line", 0, what);
2079 }
2080
2081 static void add_header_grep(struct rev_info *revs, enum grep_header_field field, const char *pattern)
2082 {
2083         append_header_grep_pattern(&revs->grep_filter, field, pattern);
2084 }
2085
2086 static void add_message_grep(struct rev_info *revs, const char *pattern)
2087 {
2088         add_grep(revs, pattern, GREP_PATTERN_BODY);
2089 }
2090
2091 static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv,
2092                                int *unkc, const char **unkv,
2093                                const struct setup_revision_opt* opt)
2094 {
2095         const char *arg = argv[0];
2096         const char *optarg;
2097         int argcount;
2098         const unsigned hexsz = the_hash_algo->hexsz;
2099
2100         /* pseudo revision arguments */
2101         if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") ||
2102             !strcmp(arg, "--tags") || !strcmp(arg, "--remotes") ||
2103             !strcmp(arg, "--reflog") || !strcmp(arg, "--not") ||
2104             !strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk") ||
2105             !strcmp(arg, "--bisect") || starts_with(arg, "--glob=") ||
2106             !strcmp(arg, "--indexed-objects") ||
2107             !strcmp(arg, "--alternate-refs") ||
2108             starts_with(arg, "--exclude=") ||
2109             starts_with(arg, "--branches=") || starts_with(arg, "--tags=") ||
2110             starts_with(arg, "--remotes=") || starts_with(arg, "--no-walk="))
2111         {
2112                 unkv[(*unkc)++] = arg;
2113                 return 1;
2114         }
2115
2116         if ((argcount = parse_long_opt("max-count", argv, &optarg))) {
2117                 revs->max_count = atoi(optarg);
2118                 revs->no_walk = 0;
2119                 return argcount;
2120         } else if ((argcount = parse_long_opt("skip", argv, &optarg))) {
2121                 revs->skip_count = atoi(optarg);
2122                 return argcount;
2123         } else if ((*arg == '-') && isdigit(arg[1])) {
2124                 /* accept -<digit>, like traditional "head" */
2125                 if (strtol_i(arg + 1, 10, &revs->max_count) < 0 ||
2126                     revs->max_count < 0)
2127                         die("'%s': not a non-negative integer", arg + 1);
2128                 revs->no_walk = 0;
2129         } else if (!strcmp(arg, "-n")) {
2130                 if (argc <= 1)
2131                         return error("-n requires an argument");
2132                 revs->max_count = atoi(argv[1]);
2133                 revs->no_walk = 0;
2134                 return 2;
2135         } else if (skip_prefix(arg, "-n", &optarg)) {
2136                 revs->max_count = atoi(optarg);
2137                 revs->no_walk = 0;
2138         } else if ((argcount = parse_long_opt("max-age", argv, &optarg))) {
2139                 revs->max_age = atoi(optarg);
2140                 return argcount;
2141         } else if ((argcount = parse_long_opt("since", argv, &optarg))) {
2142                 revs->max_age = approxidate(optarg);
2143                 return argcount;
2144         } else if ((argcount = parse_long_opt("after", argv, &optarg))) {
2145                 revs->max_age = approxidate(optarg);
2146                 return argcount;
2147         } else if ((argcount = parse_long_opt("min-age", argv, &optarg))) {
2148                 revs->min_age = atoi(optarg);
2149                 return argcount;
2150         } else if ((argcount = parse_long_opt("before", argv, &optarg))) {
2151                 revs->min_age = approxidate(optarg);
2152                 return argcount;
2153         } else if ((argcount = parse_long_opt("until", argv, &optarg))) {
2154                 revs->min_age = approxidate(optarg);
2155                 return argcount;
2156         } else if (!strcmp(arg, "--first-parent")) {
2157                 revs->first_parent_only = 1;
2158         } else if (!strcmp(arg, "--ancestry-path")) {
2159                 revs->ancestry_path = 1;
2160                 revs->simplify_history = 0;
2161                 revs->limited = 1;
2162         } else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) {
2163                 init_reflog_walk(&revs->reflog_info);
2164         } else if (!strcmp(arg, "--default")) {
2165                 if (argc <= 1)
2166                         return error("bad --default argument");
2167                 revs->def = argv[1];
2168                 return 2;
2169         } else if (!strcmp(arg, "--merge")) {
2170                 revs->show_merge = 1;
2171         } else if (!strcmp(arg, "--topo-order")) {
2172                 revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
2173                 revs->topo_order = 1;
2174         } else if (!strcmp(arg, "--simplify-merges")) {
2175                 revs->simplify_merges = 1;
2176                 revs->topo_order = 1;
2177                 revs->rewrite_parents = 1;
2178                 revs->simplify_history = 0;
2179                 revs->limited = 1;
2180         } else if (!strcmp(arg, "--simplify-by-decoration")) {
2181                 revs->simplify_merges = 1;
2182                 revs->topo_order = 1;
2183                 revs->rewrite_parents = 1;
2184                 revs->simplify_history = 0;
2185                 revs->simplify_by_decoration = 1;
2186                 revs->limited = 1;
2187                 revs->prune = 1;
2188         } else if (!strcmp(arg, "--date-order")) {
2189                 revs->sort_order = REV_SORT_BY_COMMIT_DATE;
2190                 revs->topo_order = 1;
2191         } else if (!strcmp(arg, "--author-date-order")) {
2192                 revs->sort_order = REV_SORT_BY_AUTHOR_DATE;
2193                 revs->topo_order = 1;
2194         } else if (!strcmp(arg, "--early-output")) {
2195                 revs->early_output = 100;
2196                 revs->topo_order = 1;
2197         } else if (skip_prefix(arg, "--early-output=", &optarg)) {
2198                 if (strtoul_ui(optarg, 10, &revs->early_output) < 0)
2199                         die("'%s': not a non-negative integer", optarg);
2200                 revs->topo_order = 1;
2201         } else if (!strcmp(arg, "--parents")) {
2202                 revs->rewrite_parents = 1;
2203                 revs->print_parents = 1;
2204         } else if (!strcmp(arg, "--dense")) {
2205                 revs->dense = 1;
2206         } else if (!strcmp(arg, "--sparse")) {
2207                 revs->dense = 0;
2208         } else if (!strcmp(arg, "--in-commit-order")) {
2209                 revs->tree_blobs_in_commit_order = 1;
2210         } else if (!strcmp(arg, "--remove-empty")) {
2211                 revs->remove_empty_trees = 1;
2212         } else if (!strcmp(arg, "--merges")) {
2213                 revs->min_parents = 2;
2214         } else if (!strcmp(arg, "--no-merges")) {
2215                 revs->max_parents = 1;
2216         } else if (skip_prefix(arg, "--min-parents=", &optarg)) {
2217                 revs->min_parents = atoi(optarg);
2218         } else if (!strcmp(arg, "--no-min-parents")) {
2219                 revs->min_parents = 0;
2220         } else if (skip_prefix(arg, "--max-parents=", &optarg)) {
2221                 revs->max_parents = atoi(optarg);
2222         } else if (!strcmp(arg, "--no-max-parents")) {
2223                 revs->max_parents = -1;
2224         } else if (!strcmp(arg, "--boundary")) {
2225                 revs->boundary = 1;
2226         } else if (!strcmp(arg, "--left-right")) {
2227                 revs->left_right = 1;
2228         } else if (!strcmp(arg, "--left-only")) {
2229                 if (revs->right_only)
2230                         die("--left-only is incompatible with --right-only"
2231                             " or --cherry");
2232                 revs->left_only = 1;
2233         } else if (!strcmp(arg, "--right-only")) {
2234                 if (revs->left_only)
2235                         die("--right-only is incompatible with --left-only");
2236                 revs->right_only = 1;
2237         } else if (!strcmp(arg, "--cherry")) {
2238                 if (revs->left_only)
2239                         die("--cherry is incompatible with --left-only");
2240                 revs->cherry_mark = 1;
2241                 revs->right_only = 1;
2242                 revs->max_parents = 1;
2243                 revs->limited = 1;
2244         } else if (!strcmp(arg, "--count")) {
2245                 revs->count = 1;
2246         } else if (!strcmp(arg, "--cherry-mark")) {
2247                 if (revs->cherry_pick)
2248                         die("--cherry-mark is incompatible with --cherry-pick");
2249                 revs->cherry_mark = 1;
2250                 revs->limited = 1; /* needs limit_list() */
2251         } else if (!strcmp(arg, "--cherry-pick")) {
2252                 if (revs->cherry_mark)
2253                         die("--cherry-pick is incompatible with --cherry-mark");
2254                 revs->cherry_pick = 1;
2255                 revs->limited = 1;
2256         } else if (!strcmp(arg, "--objects")) {
2257                 revs->tag_objects = 1;
2258                 revs->tree_objects = 1;
2259                 revs->blob_objects = 1;
2260         } else if (!strcmp(arg, "--objects-edge")) {
2261                 revs->tag_objects = 1;
2262                 revs->tree_objects = 1;
2263                 revs->blob_objects = 1;
2264                 revs->edge_hint = 1;
2265         } else if (!strcmp(arg, "--objects-edge-aggressive")) {
2266                 revs->tag_objects = 1;
2267                 revs->tree_objects = 1;
2268                 revs->blob_objects = 1;
2269                 revs->edge_hint = 1;
2270                 revs->edge_hint_aggressive = 1;
2271         } else if (!strcmp(arg, "--verify-objects")) {
2272                 revs->tag_objects = 1;
2273                 revs->tree_objects = 1;
2274                 revs->blob_objects = 1;
2275                 revs->verify_objects = 1;
2276         } else if (!strcmp(arg, "--unpacked")) {
2277                 revs->unpacked = 1;
2278         } else if (starts_with(arg, "--unpacked=")) {
2279                 die("--unpacked=<packfile> no longer supported.");
2280         } else if (!strcmp(arg, "-r")) {
2281                 revs->diff = 1;
2282                 revs->diffopt.flags.recursive = 1;
2283         } else if (!strcmp(arg, "-t")) {
2284                 revs->diff = 1;
2285                 revs->diffopt.flags.recursive = 1;
2286                 revs->diffopt.flags.tree_in_recursive = 1;
2287         } else if (!strcmp(arg, "-m")) {
2288                 revs->ignore_merges = 0;
2289         } else if (!strcmp(arg, "-c")) {
2290                 revs->diff = 1;
2291                 revs->dense_combined_merges = 0;
2292                 revs->combine_merges = 1;
2293         } else if (!strcmp(arg, "--combined-all-paths")) {
2294                 revs->diff = 1;
2295                 revs->combined_all_paths = 1;
2296         } else if (!strcmp(arg, "--cc")) {
2297                 revs->diff = 1;
2298                 revs->dense_combined_merges = 1;
2299                 revs->combine_merges = 1;
2300         } else if (!strcmp(arg, "-v")) {
2301                 revs->verbose_header = 1;
2302         } else if (!strcmp(arg, "--pretty")) {
2303                 revs->verbose_header = 1;
2304                 revs->pretty_given = 1;
2305                 get_commit_format(NULL, revs);
2306         } else if (skip_prefix(arg, "--pretty=", &optarg) ||
2307                    skip_prefix(arg, "--format=", &optarg)) {
2308                 /*
2309                  * Detached form ("--pretty X" as opposed to "--pretty=X")
2310                  * not allowed, since the argument is optional.
2311                  */
2312                 revs->verbose_header = 1;
2313                 revs->pretty_given = 1;
2314                 get_commit_format(optarg, revs);
2315         } else if (!strcmp(arg, "--expand-tabs")) {
2316                 revs->expand_tabs_in_log = 8;
2317         } else if (!strcmp(arg, "--no-expand-tabs")) {
2318                 revs->expand_tabs_in_log = 0;
2319         } else if (skip_prefix(arg, "--expand-tabs=", &arg)) {
2320                 int val;
2321                 if (strtol_i(arg, 10, &val) < 0 || val < 0)
2322                         die("'%s': not a non-negative integer", arg);
2323                 revs->expand_tabs_in_log = val;
2324         } else if (!strcmp(arg, "--show-notes") || !strcmp(arg, "--notes")) {
2325                 enable_default_display_notes(&revs->notes_opt, &revs->show_notes);
2326                 revs->show_notes_given = 1;
2327         } else if (!strcmp(arg, "--show-signature")) {
2328                 revs->show_signature = 1;
2329         } else if (!strcmp(arg, "--no-show-signature")) {
2330                 revs->show_signature = 0;
2331         } else if (!strcmp(arg, "--show-linear-break")) {
2332                 revs->break_bar = "                    ..........";
2333                 revs->track_linear = 1;
2334                 revs->track_first_time = 1;
2335         } else if (skip_prefix(arg, "--show-linear-break=", &optarg)) {
2336                 revs->break_bar = xstrdup(optarg);
2337                 revs->track_linear = 1;
2338                 revs->track_first_time = 1;
2339         } else if (skip_prefix(arg, "--show-notes=", &optarg) ||
2340                    skip_prefix(arg, "--notes=", &optarg)) {
2341                 if (starts_with(arg, "--show-notes=") &&
2342                     revs->notes_opt.use_default_notes < 0)
2343                         revs->notes_opt.use_default_notes = 1;
2344                 enable_ref_display_notes(&revs->notes_opt, &revs->show_notes, optarg);
2345                 revs->show_notes_given = 1;
2346         } else if (!strcmp(arg, "--no-notes")) {
2347                 disable_display_notes(&revs->notes_opt, &revs->show_notes);
2348                 revs->show_notes_given = 1;
2349         } else if (!strcmp(arg, "--standard-notes")) {
2350                 revs->show_notes_given = 1;
2351                 revs->notes_opt.use_default_notes = 1;
2352         } else if (!strcmp(arg, "--no-standard-notes")) {
2353                 revs->notes_opt.use_default_notes = 0;
2354         } else if (!strcmp(arg, "--oneline")) {
2355                 revs->verbose_header = 1;
2356                 get_commit_format("oneline", revs);
2357                 revs->pretty_given = 1;
2358                 revs->abbrev_commit = 1;
2359         } else if (!strcmp(arg, "--graph")) {
2360                 revs->topo_order = 1;
2361                 revs->rewrite_parents = 1;
2362                 revs->graph = graph_init(revs);
2363         } else if (!strcmp(arg, "--root")) {
2364                 revs->show_root_diff = 1;
2365         } else if (!strcmp(arg, "--no-commit-id")) {
2366                 revs->no_commit_id = 1;
2367         } else if (!strcmp(arg, "--always")) {
2368                 revs->always_show_header = 1;
2369         } else if (!strcmp(arg, "--no-abbrev")) {
2370                 revs->abbrev = 0;
2371         } else if (!strcmp(arg, "--abbrev")) {
2372                 revs->abbrev = DEFAULT_ABBREV;
2373         } else if (skip_prefix(arg, "--abbrev=", &optarg)) {
2374                 revs->abbrev = strtoul(optarg, NULL, 10);
2375                 if (revs->abbrev < MINIMUM_ABBREV)
2376                         revs->abbrev = MINIMUM_ABBREV;
2377                 else if (revs->abbrev > hexsz)
2378                         revs->abbrev = hexsz;
2379         } else if (!strcmp(arg, "--abbrev-commit")) {
2380                 revs->abbrev_commit = 1;
2381                 revs->abbrev_commit_given = 1;
2382         } else if (!strcmp(arg, "--no-abbrev-commit")) {
2383                 revs->abbrev_commit = 0;
2384         } else if (!strcmp(arg, "--full-diff")) {
2385                 revs->diff = 1;
2386                 revs->full_diff = 1;
2387         } else if (!strcmp(arg, "--full-history")) {
2388                 revs->simplify_history = 0;
2389         } else if (!strcmp(arg, "--relative-date")) {
2390                 revs->date_mode.type = DATE_RELATIVE;
2391                 revs->date_mode_explicit = 1;
2392         } else if ((argcount = parse_long_opt("date", argv, &optarg))) {
2393                 parse_date_format(optarg, &revs->date_mode);
2394                 revs->date_mode_explicit = 1;
2395                 return argcount;
2396         } else if (!strcmp(arg, "--log-size")) {
2397                 revs->show_log_size = 1;
2398         }
2399         /*
2400          * Grepping the commit log
2401          */
2402         else if ((argcount = parse_long_opt("author", argv, &optarg))) {
2403                 add_header_grep(revs, GREP_HEADER_AUTHOR, optarg);
2404                 return argcount;
2405         } else if ((argcount = parse_long_opt("committer", argv, &optarg))) {
2406                 add_header_grep(revs, GREP_HEADER_COMMITTER, optarg);
2407                 return argcount;
2408         } else if ((argcount = parse_long_opt("grep-reflog", argv, &optarg))) {
2409                 add_header_grep(revs, GREP_HEADER_REFLOG, optarg);
2410                 return argcount;
2411         } else if ((argcount = parse_long_opt("grep", argv, &optarg))) {
2412                 add_message_grep(revs, optarg);
2413                 return argcount;
2414         } else if (!strcmp(arg, "--grep-debug")) {
2415                 revs->grep_filter.debug = 1;
2416         } else if (!strcmp(arg, "--basic-regexp")) {
2417                 revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_BRE;
2418         } else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) {
2419                 revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_ERE;
2420         } else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) {
2421                 revs->grep_filter.ignore_case = 1;
2422                 revs->diffopt.pickaxe_opts |= DIFF_PICKAXE_IGNORE_CASE;
2423         } else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) {
2424                 revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_FIXED;
2425         } else if (!strcmp(arg, "--perl-regexp") || !strcmp(arg, "-P")) {
2426                 revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_PCRE;
2427         } else if (!strcmp(arg, "--all-match")) {
2428                 revs->grep_filter.all_match = 1;
2429         } else if (!strcmp(arg, "--invert-grep")) {
2430                 revs->invert_grep = 1;
2431         } else if ((argcount = parse_long_opt("encoding", argv, &optarg))) {
2432                 if (strcmp(optarg, "none"))
2433                         git_log_output_encoding = xstrdup(optarg);
2434                 else
2435                         git_log_output_encoding = "";
2436                 return argcount;
2437         } else if (!strcmp(arg, "--reverse")) {
2438                 revs->reverse ^= 1;
2439         } else if (!strcmp(arg, "--children")) {
2440                 revs->children.name = "children";
2441                 revs->limited = 1;
2442         } else if (!strcmp(arg, "--ignore-missing")) {
2443                 revs->ignore_missing = 1;
2444         } else if (opt && opt->allow_exclude_promisor_objects &&
2445                    !strcmp(arg, "--exclude-promisor-objects")) {
2446                 if (fetch_if_missing)
2447                         BUG("exclude_promisor_objects can only be used when fetch_if_missing is 0");
2448                 revs->exclude_promisor_objects = 1;
2449         } else {
2450                 int opts = diff_opt_parse(&revs->diffopt, argv, argc, revs->prefix);
2451                 if (!opts)
2452                         unkv[(*unkc)++] = arg;
2453                 return opts;
2454         }
2455         if (revs->graph && revs->track_linear)
2456                 die("--show-linear-break and --graph are incompatible");
2457
2458         return 1;
2459 }
2460
2461 void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx,
2462                         const struct option *options,
2463                         const char * const usagestr[])
2464 {
2465         int n = handle_revision_opt(revs, ctx->argc, ctx->argv,
2466                                     &ctx->cpidx, ctx->out, NULL);
2467         if (n <= 0) {
2468                 error("unknown option `%s'", ctx->argv[0]);
2469                 usage_with_options(usagestr, options);
2470         }
2471         ctx->argv += n;
2472         ctx->argc -= n;
2473 }
2474
2475 static int for_each_bisect_ref(struct ref_store *refs, each_ref_fn fn,
2476                                void *cb_data, const char *term)
2477 {
2478         struct strbuf bisect_refs = STRBUF_INIT;
2479         int status;
2480         strbuf_addf(&bisect_refs, "refs/bisect/%s", term);
2481         status = refs_for_each_fullref_in(refs, bisect_refs.buf, fn, cb_data, 0);
2482         strbuf_release(&bisect_refs);
2483         return status;
2484 }
2485
2486 static int for_each_bad_bisect_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
2487 {
2488         return for_each_bisect_ref(refs, fn, cb_data, term_bad);
2489 }
2490
2491 static int for_each_good_bisect_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
2492 {
2493         return for_each_bisect_ref(refs, fn, cb_data, term_good);
2494 }
2495
2496 static int handle_revision_pseudo_opt(const char *submodule,
2497                                 struct rev_info *revs,
2498                                 int argc, const char **argv, int *flags)
2499 {
2500         const char *arg = argv[0];
2501         const char *optarg;
2502         struct ref_store *refs;
2503         int argcount;
2504
2505         if (submodule) {
2506                 /*
2507                  * We need some something like get_submodule_worktrees()
2508                  * before we can go through all worktrees of a submodule,
2509                  * .e.g with adding all HEADs from --all, which is not
2510                  * supported right now, so stick to single worktree.
2511                  */
2512                 if (!revs->single_worktree)
2513                         BUG("--single-worktree cannot be used together with submodule");
2514                 refs = get_submodule_ref_store(submodule);
2515         } else
2516                 refs = get_main_ref_store(revs->repo);
2517
2518         /*
2519          * NOTE!
2520          *
2521          * Commands like "git shortlog" will not accept the options below
2522          * unless parse_revision_opt queues them (as opposed to erroring
2523          * out).
2524          *
2525          * When implementing your new pseudo-option, remember to
2526          * register it in the list at the top of handle_revision_opt.
2527          */
2528         if (!strcmp(arg, "--all")) {
2529                 handle_refs(refs, revs, *flags, refs_for_each_ref);
2530                 handle_refs(refs, revs, *flags, refs_head_ref);
2531                 if (!revs->single_worktree) {
2532                         struct all_refs_cb cb;
2533
2534                         init_all_refs_cb(&cb, revs, *flags);
2535                         other_head_refs(handle_one_ref, &cb);
2536                 }
2537                 clear_ref_exclusion(&revs->ref_excludes);
2538         } else if (!strcmp(arg, "--branches")) {
2539                 handle_refs(refs, revs, *flags, refs_for_each_branch_ref);
2540                 clear_ref_exclusion(&revs->ref_excludes);
2541         } else if (!strcmp(arg, "--bisect")) {
2542                 read_bisect_terms(&term_bad, &term_good);
2543                 handle_refs(refs, revs, *flags, for_each_bad_bisect_ref);
2544                 handle_refs(refs, revs, *flags ^ (UNINTERESTING | BOTTOM),
2545                             for_each_good_bisect_ref);
2546                 revs->bisect = 1;
2547         } else if (!strcmp(arg, "--tags")) {
2548                 handle_refs(refs, revs, *flags, refs_for_each_tag_ref);
2549                 clear_ref_exclusion(&revs->ref_excludes);
2550         } else if (!strcmp(arg, "--remotes")) {
2551                 handle_refs(refs, revs, *flags, refs_for_each_remote_ref);
2552                 clear_ref_exclusion(&revs->ref_excludes);
2553         } else if ((argcount = parse_long_opt("glob", argv, &optarg))) {
2554                 struct all_refs_cb cb;
2555                 init_all_refs_cb(&cb, revs, *flags);
2556                 for_each_glob_ref(handle_one_ref, optarg, &cb);
2557                 clear_ref_exclusion(&revs->ref_excludes);
2558                 return argcount;
2559         } else if ((argcount = parse_long_opt("exclude", argv, &optarg))) {
2560                 add_ref_exclusion(&revs->ref_excludes, optarg);
2561                 return argcount;
2562         } else if (skip_prefix(arg, "--branches=", &optarg)) {
2563                 struct all_refs_cb cb;
2564                 init_all_refs_cb(&cb, revs, *flags);
2565                 for_each_glob_ref_in(handle_one_ref, optarg, "refs/heads/", &cb);
2566                 clear_ref_exclusion(&revs->ref_excludes);
2567         } else if (skip_prefix(arg, "--tags=", &optarg)) {
2568                 struct all_refs_cb cb;
2569                 init_all_refs_cb(&cb, revs, *flags);
2570                 for_each_glob_ref_in(handle_one_ref, optarg, "refs/tags/", &cb);
2571                 clear_ref_exclusion(&revs->ref_excludes);
2572         } else if (skip_prefix(arg, "--remotes=", &optarg)) {
2573                 struct all_refs_cb cb;
2574                 init_all_refs_cb(&cb, revs, *flags);
2575                 for_each_glob_ref_in(handle_one_ref, optarg, "refs/remotes/", &cb);
2576                 clear_ref_exclusion(&revs->ref_excludes);
2577         } else if (!strcmp(arg, "--reflog")) {
2578                 add_reflogs_to_pending(revs, *flags);
2579         } else if (!strcmp(arg, "--indexed-objects")) {
2580                 add_index_objects_to_pending(revs, *flags);
2581         } else if (!strcmp(arg, "--alternate-refs")) {
2582                 add_alternate_refs_to_pending(revs, *flags);
2583         } else if (!strcmp(arg, "--not")) {
2584                 *flags ^= UNINTERESTING | BOTTOM;
2585         } else if (!strcmp(arg, "--no-walk")) {
2586                 revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
2587         } else if (skip_prefix(arg, "--no-walk=", &optarg)) {
2588                 /*
2589                  * Detached form ("--no-walk X" as opposed to "--no-walk=X")
2590                  * not allowed, since the argument is optional.
2591                  */
2592                 if (!strcmp(optarg, "sorted"))
2593                         revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
2594                 else if (!strcmp(optarg, "unsorted"))
2595                         revs->no_walk = REVISION_WALK_NO_WALK_UNSORTED;
2596                 else
2597                         return error("invalid argument to --no-walk");
2598         } else if (!strcmp(arg, "--do-walk")) {
2599                 revs->no_walk = 0;
2600         } else if (!strcmp(arg, "--single-worktree")) {
2601                 revs->single_worktree = 1;
2602         } else {
2603                 return 0;
2604         }
2605
2606         return 1;
2607 }
2608
2609 static void NORETURN diagnose_missing_default(const char *def)
2610 {
2611         int flags;
2612         const char *refname;
2613
2614         refname = resolve_ref_unsafe(def, 0, NULL, &flags);
2615         if (!refname || !(flags & REF_ISSYMREF) || (flags & REF_ISBROKEN))
2616                 die(_("your current branch appears to be broken"));
2617
2618         skip_prefix(refname, "refs/heads/", &refname);
2619         die(_("your current branch '%s' does not have any commits yet"),
2620             refname);
2621 }
2622
2623 /*
2624  * Parse revision information, filling in the "rev_info" structure,
2625  * and removing the used arguments from the argument list.
2626  *
2627  * Returns the number of arguments left that weren't recognized
2628  * (which are also moved to the head of the argument list)
2629  */
2630 int setup_revisions(int argc, const char **argv, struct rev_info *revs, struct setup_revision_opt *opt)
2631 {
2632         int i, flags, left, seen_dashdash, got_rev_arg = 0, revarg_opt;
2633         struct argv_array prune_data = ARGV_ARRAY_INIT;
2634         const char *submodule = NULL;
2635         int seen_end_of_options = 0;
2636
2637         if (opt)
2638                 submodule = opt->submodule;
2639
2640         /* First, search for "--" */
2641         if (opt && opt->assume_dashdash) {
2642                 seen_dashdash = 1;
2643         } else {
2644                 seen_dashdash = 0;
2645                 for (i = 1; i < argc; i++) {
2646                         const char *arg = argv[i];
2647                         if (strcmp(arg, "--"))
2648                                 continue;
2649                         argv[i] = NULL;
2650                         argc = i;
2651                         if (argv[i + 1])
2652                                 argv_array_pushv(&prune_data, argv + i + 1);
2653                         seen_dashdash = 1;
2654                         break;
2655                 }
2656         }
2657
2658         /* Second, deal with arguments and options */
2659         flags = 0;
2660         revarg_opt = opt ? opt->revarg_opt : 0;
2661         if (seen_dashdash)
2662                 revarg_opt |= REVARG_CANNOT_BE_FILENAME;
2663         for (left = i = 1; i < argc; i++) {
2664                 const char *arg = argv[i];
2665                 if (!seen_end_of_options && *arg == '-') {
2666                         int opts;
2667
2668                         opts = handle_revision_pseudo_opt(submodule,
2669                                                 revs, argc - i, argv + i,
2670                                                 &flags);
2671                         if (opts > 0) {
2672                                 i += opts - 1;
2673                                 continue;
2674                         }
2675
2676                         if (!strcmp(arg, "--stdin")) {
2677                                 if (revs->disable_stdin) {
2678                                         argv[left++] = arg;
2679                                         continue;
2680                                 }
2681                                 if (revs->read_from_stdin++)
2682                                         die("--stdin given twice?");
2683                                 read_revisions_from_stdin(revs, &prune_data);
2684                                 continue;
2685                         }
2686
2687                         if (!strcmp(arg, "--end-of-options")) {
2688                                 seen_end_of_options = 1;
2689                                 continue;
2690                         }
2691
2692                         opts = handle_revision_opt(revs, argc - i, argv + i,
2693                                                    &left, argv, opt);
2694                         if (opts > 0) {
2695                                 i += opts - 1;
2696                                 continue;
2697                         }
2698                         if (opts < 0)
2699                                 exit(128);
2700                         continue;
2701                 }
2702
2703
2704                 if (handle_revision_arg(arg, revs, flags, revarg_opt)) {
2705                         int j;
2706                         if (seen_dashdash || *arg == '^')
2707                                 die("bad revision '%s'", arg);
2708
2709                         /* If we didn't have a "--":
2710                          * (1) all filenames must exist;
2711                          * (2) all rev-args must not be interpretable
2712                          *     as a valid filename.
2713                          * but the latter we have checked in the main loop.
2714                          */
2715                         for (j = i; j < argc; j++)
2716                                 verify_filename(revs->prefix, argv[j], j == i);
2717
2718                         argv_array_pushv(&prune_data, argv + i);
2719                         break;
2720                 }
2721                 else
2722                         got_rev_arg = 1;
2723         }
2724
2725         if (prune_data.argc) {
2726                 /*
2727                  * If we need to introduce the magic "a lone ':' means no
2728                  * pathspec whatsoever", here is the place to do so.
2729                  *
2730                  * if (prune_data.nr == 1 && !strcmp(prune_data[0], ":")) {
2731                  *      prune_data.nr = 0;
2732                  *      prune_data.alloc = 0;
2733                  *      free(prune_data.path);
2734                  *      prune_data.path = NULL;
2735                  * } else {
2736                  *      terminate prune_data.alloc with NULL and
2737                  *      call init_pathspec() to set revs->prune_data here.
2738                  * }
2739                  */
2740                 parse_pathspec(&revs->prune_data, 0, 0,
2741                                revs->prefix, prune_data.argv);
2742         }
2743         argv_array_clear(&prune_data);
2744
2745         if (revs->def == NULL)
2746                 revs->def = opt ? opt->def : NULL;
2747         if (opt && opt->tweak)
2748                 opt->tweak(revs, opt);
2749         if (revs->show_merge)
2750                 prepare_show_merge(revs);
2751         if (revs->def && !revs->pending.nr && !revs->rev_input_given && !got_rev_arg) {
2752                 struct object_id oid;
2753                 struct object *object;
2754                 struct object_context oc;
2755                 if (get_oid_with_context(revs->repo, revs->def, 0, &oid, &oc))
2756                         diagnose_missing_default(revs->def);
2757                 object = get_reference(revs, revs->def, &oid, 0);
2758                 add_pending_object_with_mode(revs, object, revs->def, oc.mode);
2759         }
2760
2761         /* Did the user ask for any diff output? Run the diff! */
2762         if (revs->diffopt.output_format & ~DIFF_FORMAT_NO_OUTPUT)
2763                 revs->diff = 1;
2764
2765         /* Pickaxe, diff-filter and rename following need diffs */
2766         if ((revs->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
2767             revs->diffopt.filter ||
2768             revs->diffopt.flags.follow_renames)
2769                 revs->diff = 1;
2770
2771         if (revs->diffopt.objfind)
2772                 revs->simplify_history = 0;
2773
2774         if (revs->topo_order && !generation_numbers_enabled(the_repository))
2775                 revs->limited = 1;
2776
2777         if (revs->prune_data.nr) {
2778                 copy_pathspec(&revs->pruning.pathspec, &revs->prune_data);
2779                 /* Can't prune commits with rename following: the paths change.. */
2780                 if (!revs->diffopt.flags.follow_renames)
2781                         revs->prune = 1;
2782                 if (!revs->full_diff)
2783                         copy_pathspec(&revs->diffopt.pathspec,
2784                                       &revs->prune_data);
2785         }
2786         if (revs->combine_merges)
2787                 revs->ignore_merges = 0;
2788         if (revs->combined_all_paths && !revs->combine_merges)
2789                 die("--combined-all-paths makes no sense without -c or --cc");
2790
2791         revs->diffopt.abbrev = revs->abbrev;
2792
2793         if (revs->line_level_traverse) {
2794                 revs->limited = 1;
2795                 revs->topo_order = 1;
2796         }
2797
2798         diff_setup_done(&revs->diffopt);
2799
2800         grep_commit_pattern_type(GREP_PATTERN_TYPE_UNSPECIFIED,
2801                                  &revs->grep_filter);
2802         if (!is_encoding_utf8(get_log_output_encoding()))
2803                 revs->grep_filter.ignore_locale = 1;
2804         compile_grep_patterns(&revs->grep_filter);
2805
2806         if (revs->reverse && revs->reflog_info)
2807                 die("cannot combine --reverse with --walk-reflogs");
2808         if (revs->reflog_info && revs->limited)
2809                 die("cannot combine --walk-reflogs with history-limiting options");
2810         if (revs->rewrite_parents && revs->children.name)
2811                 die("cannot combine --parents and --children");
2812
2813         /*
2814          * Limitations on the graph functionality
2815          */
2816         if (revs->reverse && revs->graph)
2817                 die("cannot combine --reverse with --graph");
2818
2819         if (revs->reflog_info && revs->graph)
2820                 die("cannot combine --walk-reflogs with --graph");
2821         if (revs->no_walk && revs->graph)
2822                 die("cannot combine --no-walk with --graph");
2823         if (!revs->reflog_info && revs->grep_filter.use_reflog_filter)
2824                 die("cannot use --grep-reflog without --walk-reflogs");
2825
2826         if (revs->first_parent_only && revs->bisect)
2827                 die(_("--first-parent is incompatible with --bisect"));
2828
2829         if (revs->line_level_traverse &&
2830             (revs->diffopt.output_format & ~(DIFF_FORMAT_PATCH | DIFF_FORMAT_NO_OUTPUT)))
2831                 die(_("-L does not yet support diff formats besides -p and -s"));
2832
2833         if (revs->expand_tabs_in_log < 0)
2834                 revs->expand_tabs_in_log = revs->expand_tabs_in_log_default;
2835
2836         return left;
2837 }
2838
2839 static void add_child(struct rev_info *revs, struct commit *parent, struct commit *child)
2840 {
2841         struct commit_list *l = xcalloc(1, sizeof(*l));
2842
2843         l->item = child;
2844         l->next = add_decoration(&revs->children, &parent->object, l);
2845 }
2846
2847 static int remove_duplicate_parents(struct rev_info *revs, struct commit *commit)
2848 {
2849         struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
2850         struct commit_list **pp, *p;
2851         int surviving_parents;
2852
2853         /* Examine existing parents while marking ones we have seen... */
2854         pp = &commit->parents;
2855         surviving_parents = 0;
2856         while ((p = *pp) != NULL) {
2857                 struct commit *parent = p->item;
2858                 if (parent->object.flags & TMP_MARK) {
2859                         *pp = p->next;
2860                         if (ts)
2861                                 compact_treesame(revs, commit, surviving_parents);
2862                         continue;
2863                 }
2864                 parent->object.flags |= TMP_MARK;
2865                 surviving_parents++;
2866                 pp = &p->next;
2867         }
2868         /* clear the temporary mark */
2869         for (p = commit->parents; p; p = p->next) {
2870                 p->item->object.flags &= ~TMP_MARK;
2871         }
2872         /* no update_treesame() - removing duplicates can't affect TREESAME */
2873         return surviving_parents;
2874 }
2875
2876 struct merge_simplify_state {
2877         struct commit *simplified;
2878 };
2879
2880 static struct merge_simplify_state *locate_simplify_state(struct rev_info *revs, struct commit *commit)
2881 {
2882         struct merge_simplify_state *st;
2883
2884         st = lookup_decoration(&revs->merge_simplification, &commit->object);
2885         if (!st) {
2886                 st = xcalloc(1, sizeof(*st));
2887                 add_decoration(&revs->merge_simplification, &commit->object, st);
2888         }
2889         return st;
2890 }
2891
2892 static int mark_redundant_parents(struct commit *commit)
2893 {
2894         struct commit_list *h = reduce_heads(commit->parents);
2895         int i = 0, marked = 0;
2896         struct commit_list *po, *pn;
2897
2898         /* Want these for sanity-checking only */
2899         int orig_cnt = commit_list_count(commit->parents);
2900         int cnt = commit_list_count(h);
2901
2902         /*
2903          * Not ready to remove items yet, just mark them for now, based
2904          * on the output of reduce_heads(). reduce_heads outputs the reduced
2905          * set in its original order, so this isn't too hard.
2906          */
2907         po = commit->parents;
2908         pn = h;
2909         while (po) {
2910                 if (pn && po->item == pn->item) {
2911                         pn = pn->next;
2912                         i++;
2913                 } else {
2914                         po->item->object.flags |= TMP_MARK;
2915                         marked++;
2916                 }
2917                 po=po->next;
2918         }
2919
2920         if (i != cnt || cnt+marked != orig_cnt)
2921                 die("mark_redundant_parents %d %d %d %d", orig_cnt, cnt, i, marked);
2922
2923         free_commit_list(h);
2924
2925         return marked;
2926 }
2927
2928 static int mark_treesame_root_parents(struct commit *commit)
2929 {
2930         struct commit_list *p;
2931         int marked = 0;
2932
2933         for (p = commit->parents; p; p = p->next) {
2934                 struct commit *parent = p->item;
2935                 if (!parent->parents && (parent->object.flags & TREESAME)) {
2936                         parent->object.flags |= TMP_MARK;
2937                         marked++;
2938                 }
2939         }
2940
2941         return marked;
2942 }
2943
2944 /*
2945  * Awkward naming - this means one parent we are TREESAME to.
2946  * cf mark_treesame_root_parents: root parents that are TREESAME (to an
2947  * empty tree). Better name suggestions?
2948  */
2949 static int leave_one_treesame_to_parent(struct rev_info *revs, struct commit *commit)
2950 {
2951         struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
2952         struct commit *unmarked = NULL, *marked = NULL;
2953         struct commit_list *p;
2954         unsigned n;
2955
2956         for (p = commit->parents, n = 0; p; p = p->next, n++) {
2957                 if (ts->treesame[n]) {
2958                         if (p->item->object.flags & TMP_MARK) {
2959                                 if (!marked)
2960                                         marked = p->item;
2961                         } else {
2962                                 if (!unmarked) {
2963                                         unmarked = p->item;
2964                                         break;
2965                                 }
2966                         }
2967                 }
2968         }
2969
2970         /*
2971          * If we are TREESAME to a marked-for-deletion parent, but not to any
2972          * unmarked parents, unmark the first TREESAME parent. This is the
2973          * parent that the default simplify_history==1 scan would have followed,
2974          * and it doesn't make sense to omit that path when asking for a
2975          * simplified full history. Retaining it improves the chances of
2976          * understanding odd missed merges that took an old version of a file.
2977          *
2978          * Example:
2979          *
2980          *   I--------*X       A modified the file, but mainline merge X used
2981          *    \       /        "-s ours", so took the version from I. X is
2982          *     `-*A--'         TREESAME to I and !TREESAME to A.
2983          *
2984          * Default log from X would produce "I". Without this check,
2985          * --full-history --simplify-merges would produce "I-A-X", showing
2986          * the merge commit X and that it changed A, but not making clear that
2987          * it had just taken the I version. With this check, the topology above
2988          * is retained.
2989          *
2990          * Note that it is possible that the simplification chooses a different
2991          * TREESAME parent from the default, in which case this test doesn't
2992          * activate, and we _do_ drop the default parent. Example:
2993          *
2994          *   I------X         A modified the file, but it was reverted in B,
2995          *    \    /          meaning mainline merge X is TREESAME to both
2996          *    *A-*B           parents.
2997          *
2998          * Default log would produce "I" by following the first parent;
2999          * --full-history --simplify-merges will produce "I-A-B". But this is a
3000          * reasonable result - it presents a logical full history leading from
3001          * I to X, and X is not an important merge.
3002          */
3003         if (!unmarked && marked) {
3004                 marked->object.flags &= ~TMP_MARK;
3005                 return 1;
3006         }
3007
3008         return 0;
3009 }
3010
3011 static int remove_marked_parents(struct rev_info *revs, struct commit *commit)
3012 {
3013         struct commit_list **pp, *p;
3014         int nth_parent, removed = 0;
3015
3016         pp = &commit->parents;
3017         nth_parent = 0;
3018         while ((p = *pp) != NULL) {
3019                 struct commit *parent = p->item;
3020                 if (parent->object.flags & TMP_MARK) {
3021                         parent->object.flags &= ~TMP_MARK;
3022                         *pp = p->next;
3023                         free(p);
3024                         removed++;
3025                         compact_treesame(revs, commit, nth_parent);
3026                         continue;
3027                 }
3028                 pp = &p->next;
3029                 nth_parent++;
3030         }
3031
3032         /* Removing parents can only increase TREESAMEness */
3033         if (removed && !(commit->object.flags & TREESAME))
3034                 update_treesame(revs, commit);
3035
3036         return nth_parent;
3037 }
3038
3039 static struct commit_list **simplify_one(struct rev_info *revs, struct commit *commit, struct commit_list **tail)
3040 {
3041         struct commit_list *p;
3042         struct commit *parent;
3043         struct merge_simplify_state *st, *pst;
3044         int cnt;
3045
3046         st = locate_simplify_state(revs, commit);
3047
3048         /*
3049          * Have we handled this one?
3050          */
3051         if (st->simplified)
3052                 return tail;
3053
3054         /*
3055          * An UNINTERESTING commit simplifies to itself, so does a
3056          * root commit.  We do not rewrite parents of such commit
3057          * anyway.
3058          */
3059         if ((commit->object.flags & UNINTERESTING) || !commit->parents) {
3060                 st->simplified = commit;
3061                 return tail;
3062         }
3063
3064         /*
3065          * Do we know what commit all of our parents that matter
3066          * should be rewritten to?  Otherwise we are not ready to
3067          * rewrite this one yet.
3068          */
3069         for (cnt = 0, p = commit->parents; p; p = p->next) {
3070                 pst = locate_simplify_state(revs, p->item);
3071                 if (!pst->simplified) {
3072                         tail = &commit_list_insert(p->item, tail)->next;
3073                         cnt++;
3074                 }
3075                 if (revs->first_parent_only)
3076                         break;
3077         }
3078         if (cnt) {
3079                 tail = &commit_list_insert(commit, tail)->next;
3080                 return tail;
3081         }
3082
3083         /*
3084          * Rewrite our list of parents. Note that this cannot
3085          * affect our TREESAME flags in any way - a commit is
3086          * always TREESAME to its simplification.
3087          */
3088         for (p = commit->parents; p; p = p->next) {
3089                 pst = locate_simplify_state(revs, p->item);
3090                 p->item = pst->simplified;
3091                 if (revs->first_parent_only)
3092                         break;
3093         }
3094
3095         if (revs->first_parent_only)
3096                 cnt = 1;
3097         else
3098                 cnt = remove_duplicate_parents(revs, commit);
3099
3100         /*
3101          * It is possible that we are a merge and one side branch
3102          * does not have any commit that touches the given paths;
3103          * in such a case, the immediate parent from that branch
3104          * will be rewritten to be the merge base.
3105          *
3106          *      o----X          X: the commit we are looking at;
3107          *     /    /           o: a commit that touches the paths;
3108          * ---o----'
3109          *
3110          * Further, a merge of an independent branch that doesn't
3111          * touch the path will reduce to a treesame root parent:
3112          *
3113          *  ----o----X          X: the commit we are looking at;
3114          *          /           o: a commit that touches the paths;
3115          *         r            r: a root commit not touching the paths
3116          *
3117          * Detect and simplify both cases.
3118          */
3119         if (1 < cnt) {
3120                 int marked = mark_redundant_parents(commit);
3121                 marked += mark_treesame_root_parents(commit);
3122                 if (marked)
3123                         marked -= leave_one_treesame_to_parent(revs, commit);
3124                 if (marked)
3125                         cnt = remove_marked_parents(revs, commit);
3126         }
3127
3128         /*
3129          * A commit simplifies to itself if it is a root, if it is
3130          * UNINTERESTING, if it touches the given paths, or if it is a
3131          * merge and its parents don't simplify to one relevant commit
3132          * (the first two cases are already handled at the beginning of
3133          * this function).
3134          *
3135          * Otherwise, it simplifies to what its sole relevant parent
3136          * simplifies to.
3137          */
3138         if (!cnt ||
3139             (commit->object.flags & UNINTERESTING) ||
3140             !(commit->object.flags & TREESAME) ||
3141             (parent = one_relevant_parent(revs, commit->parents)) == NULL)
3142                 st->simplified = commit;
3143         else {
3144                 pst = locate_simplify_state(revs, parent);
3145                 st->simplified = pst->simplified;
3146         }
3147         return tail;
3148 }
3149
3150 static void simplify_merges(struct rev_info *revs)
3151 {
3152         struct commit_list *list, *next;
3153         struct commit_list *yet_to_do, **tail;
3154         struct commit *commit;
3155
3156         if (!revs->prune)
3157                 return;
3158
3159         /* feed the list reversed */
3160         yet_to_do = NULL;
3161         for (list = revs->commits; list; list = next) {
3162                 commit = list->item;
3163                 next = list->next;
3164                 /*
3165                  * Do not free(list) here yet; the original list
3166                  * is used later in this function.
3167                  */
3168                 commit_list_insert(commit, &yet_to_do);
3169         }
3170         while (yet_to_do) {
3171                 list = yet_to_do;
3172                 yet_to_do = NULL;
3173                 tail = &yet_to_do;
3174                 while (list) {
3175                         commit = pop_commit(&list);
3176                         tail = simplify_one(revs, commit, tail);
3177                 }
3178         }
3179
3180         /* clean up the result, removing the simplified ones */
3181         list = revs->commits;
3182         revs->commits = NULL;
3183         tail = &revs->commits;
3184         while (list) {
3185                 struct merge_simplify_state *st;
3186
3187                 commit = pop_commit(&list);
3188                 st = locate_simplify_state(revs, commit);
3189                 if (st->simplified == commit)
3190                         tail = &commit_list_insert(commit, tail)->next;
3191         }
3192 }
3193
3194 static void set_children(struct rev_info *revs)
3195 {
3196         struct commit_list *l;
3197         for (l = revs->commits; l; l = l->next) {
3198                 struct commit *commit = l->item;
3199                 struct commit_list *p;
3200
3201                 for (p = commit->parents; p; p = p->next)
3202                         add_child(revs, p->item, commit);
3203         }
3204 }
3205
3206 void reset_revision_walk(void)
3207 {
3208         clear_object_flags(SEEN | ADDED | SHOWN | TOPO_WALK_EXPLORED | TOPO_WALK_INDEGREE);
3209 }
3210
3211 static int mark_uninteresting(const struct object_id *oid,
3212                               struct packed_git *pack,
3213                               uint32_t pos,
3214                               void *cb)
3215 {
3216         struct rev_info *revs = cb;
3217         struct object *o = parse_object(revs->repo, oid);
3218         o->flags |= UNINTERESTING | SEEN;
3219         return 0;
3220 }
3221
3222 define_commit_slab(indegree_slab, int);
3223 define_commit_slab(author_date_slab, timestamp_t);
3224
3225 struct topo_walk_info {
3226         uint32_t min_generation;
3227         struct prio_queue explore_queue;
3228         struct prio_queue indegree_queue;
3229         struct prio_queue topo_queue;
3230         struct indegree_slab indegree;
3231         struct author_date_slab author_date;
3232 };
3233
3234 static inline void test_flag_and_insert(struct prio_queue *q, struct commit *c, int flag)
3235 {
3236         if (c->object.flags & flag)
3237                 return;
3238
3239         c->object.flags |= flag;
3240         prio_queue_put(q, c);
3241 }
3242
3243 static void explore_walk_step(struct rev_info *revs)
3244 {
3245         struct topo_walk_info *info = revs->topo_walk_info;
3246         struct commit_list *p;
3247         struct commit *c = prio_queue_get(&info->explore_queue);
3248
3249         if (!c)
3250                 return;
3251
3252         if (parse_commit_gently(c, 1) < 0)
3253                 return;
3254
3255         if (revs->sort_order == REV_SORT_BY_AUTHOR_DATE)
3256                 record_author_date(&info->author_date, c);
3257
3258         if (revs->max_age != -1 && (c->date < revs->max_age))
3259                 c->object.flags |= UNINTERESTING;
3260
3261         if (process_parents(revs, c, NULL, NULL) < 0)
3262                 return;
3263
3264         if (c->object.flags & UNINTERESTING)
3265                 mark_parents_uninteresting(c);
3266
3267         for (p = c->parents; p; p = p->next)
3268                 test_flag_and_insert(&info->explore_queue, p->item, TOPO_WALK_EXPLORED);
3269 }
3270
3271 static void explore_to_depth(struct rev_info *revs,
3272                              uint32_t gen_cutoff)
3273 {
3274         struct topo_walk_info *info = revs->topo_walk_info;
3275         struct commit *c;
3276         while ((c = prio_queue_peek(&info->explore_queue)) &&
3277                c->generation >= gen_cutoff)
3278                 explore_walk_step(revs);
3279 }
3280
3281 static void indegree_walk_step(struct rev_info *revs)
3282 {
3283         struct commit_list *p;
3284         struct topo_walk_info *info = revs->topo_walk_info;
3285         struct commit *c = prio_queue_get(&info->indegree_queue);
3286
3287         if (!c)
3288                 return;
3289
3290         if (parse_commit_gently(c, 1) < 0)
3291                 return;
3292
3293         explore_to_depth(revs, c->generation);
3294
3295         for (p = c->parents; p; p = p->next) {
3296                 struct commit *parent = p->item;
3297                 int *pi = indegree_slab_at(&info->indegree, parent);
3298
3299                 if (*pi)
3300                         (*pi)++;
3301                 else
3302                         *pi = 2;
3303
3304                 test_flag_and_insert(&info->indegree_queue, parent, TOPO_WALK_INDEGREE);
3305
3306                 if (revs->first_parent_only)
3307                         return;
3308         }
3309 }
3310
3311 static void compute_indegrees_to_depth(struct rev_info *revs,
3312                                        uint32_t gen_cutoff)
3313 {
3314         struct topo_walk_info *info = revs->topo_walk_info;
3315         struct commit *c;
3316         while ((c = prio_queue_peek(&info->indegree_queue)) &&
3317                c->generation >= gen_cutoff)
3318                 indegree_walk_step(revs);
3319 }
3320
3321 static void reset_topo_walk(struct rev_info *revs)
3322 {
3323         struct topo_walk_info *info = revs->topo_walk_info;
3324
3325         clear_prio_queue(&info->explore_queue);
3326         clear_prio_queue(&info->indegree_queue);
3327         clear_prio_queue(&info->topo_queue);
3328         clear_indegree_slab(&info->indegree);
3329         clear_author_date_slab(&info->author_date);
3330
3331         FREE_AND_NULL(revs->topo_walk_info);
3332 }
3333
3334 static void init_topo_walk(struct rev_info *revs)
3335 {
3336         struct topo_walk_info *info;
3337         struct commit_list *list;
3338         if (revs->topo_walk_info)
3339                 reset_topo_walk(revs);
3340
3341         revs->topo_walk_info = xmalloc(sizeof(struct topo_walk_info));
3342         info = revs->topo_walk_info;
3343         memset(info, 0, sizeof(struct topo_walk_info));
3344
3345         init_indegree_slab(&info->indegree);
3346         memset(&info->explore_queue, 0, sizeof(info->explore_queue));
3347         memset(&info->indegree_queue, 0, sizeof(info->indegree_queue));
3348         memset(&info->topo_queue, 0, sizeof(info->topo_queue));
3349
3350         switch (revs->sort_order) {
3351         default: /* REV_SORT_IN_GRAPH_ORDER */
3352                 info->topo_queue.compare = NULL;
3353                 break;
3354         case REV_SORT_BY_COMMIT_DATE:
3355                 info->topo_queue.compare = compare_commits_by_commit_date;
3356                 break;
3357         case REV_SORT_BY_AUTHOR_DATE:
3358                 init_author_date_slab(&info->author_date);
3359                 info->topo_queue.compare = compare_commits_by_author_date;
3360                 info->topo_queue.cb_data = &info->author_date;
3361                 break;
3362         }
3363
3364         info->explore_queue.compare = compare_commits_by_gen_then_commit_date;
3365         info->indegree_queue.compare = compare_commits_by_gen_then_commit_date;
3366
3367         info->min_generation = GENERATION_NUMBER_INFINITY;
3368         for (list = revs->commits; list; list = list->next) {
3369                 struct commit *c = list->item;
3370
3371                 if (parse_commit_gently(c, 1))
3372                         continue;
3373
3374                 test_flag_and_insert(&info->explore_queue, c, TOPO_WALK_EXPLORED);
3375                 test_flag_and_insert(&info->indegree_queue, c, TOPO_WALK_INDEGREE);
3376
3377                 if (c->generation < info->min_generation)
3378                         info->min_generation = c->generation;
3379
3380                 *(indegree_slab_at(&info->indegree, c)) = 1;
3381
3382                 if (revs->sort_order == REV_SORT_BY_AUTHOR_DATE)
3383                         record_author_date(&info->author_date, c);
3384         }
3385         compute_indegrees_to_depth(revs, info->min_generation);
3386
3387         for (list = revs->commits; list; list = list->next) {
3388                 struct commit *c = list->item;
3389
3390                 if (*(indegree_slab_at(&info->indegree, c)) == 1)
3391                         prio_queue_put(&info->topo_queue, c);
3392         }
3393
3394         /*
3395          * This is unfortunate; the initial tips need to be shown
3396          * in the order given from the revision traversal machinery.
3397          */
3398         if (revs->sort_order == REV_SORT_IN_GRAPH_ORDER)
3399                 prio_queue_reverse(&info->topo_queue);
3400 }
3401
3402 static struct commit *next_topo_commit(struct rev_info *revs)
3403 {
3404         struct commit *c;
3405         struct topo_walk_info *info = revs->topo_walk_info;
3406
3407         /* pop next off of topo_queue */
3408         c = prio_queue_get(&info->topo_queue);
3409
3410         if (c)
3411                 *(indegree_slab_at(&info->indegree, c)) = 0;
3412
3413         return c;
3414 }
3415
3416 static void expand_topo_walk(struct rev_info *revs, struct commit *commit)
3417 {
3418         struct commit_list *p;
3419         struct topo_walk_info *info = revs->topo_walk_info;
3420         if (process_parents(revs, commit, NULL, NULL) < 0) {
3421                 if (!revs->ignore_missing_links)
3422                         die("Failed to traverse parents of commit %s",
3423                             oid_to_hex(&commit->object.oid));
3424         }
3425
3426         for (p = commit->parents; p; p = p->next) {
3427                 struct commit *parent = p->item;
3428                 int *pi;
3429
3430                 if (parent->object.flags & UNINTERESTING)
3431                         continue;
3432
3433                 if (parse_commit_gently(parent, 1) < 0)
3434                         continue;
3435
3436                 if (parent->generation < info->min_generation) {
3437                         info->min_generation = parent->generation;
3438                         compute_indegrees_to_depth(revs, info->min_generation);
3439                 }
3440
3441                 pi = indegree_slab_at(&info->indegree, parent);
3442
3443                 (*pi)--;
3444                 if (*pi == 1)
3445                         prio_queue_put(&info->topo_queue, parent);
3446
3447                 if (revs->first_parent_only)
3448                         return;
3449         }
3450 }
3451
3452 int prepare_revision_walk(struct rev_info *revs)
3453 {
3454         int i;
3455         struct object_array old_pending;
3456         struct commit_list **next = &revs->commits;
3457
3458         memcpy(&old_pending, &revs->pending, sizeof(old_pending));
3459         revs->pending.nr = 0;
3460         revs->pending.alloc = 0;
3461         revs->pending.objects = NULL;
3462         for (i = 0; i < old_pending.nr; i++) {
3463                 struct object_array_entry *e = old_pending.objects + i;
3464                 struct commit *commit = handle_commit(revs, e);
3465                 if (commit) {
3466                         if (!(commit->object.flags & SEEN)) {
3467                                 commit->object.flags |= SEEN;
3468                                 next = commit_list_append(commit, next);
3469                         }
3470                 }
3471         }
3472         object_array_clear(&old_pending);
3473
3474         /* Signal whether we need per-parent treesame decoration */
3475         if (revs->simplify_merges ||
3476             (revs->limited && limiting_can_increase_treesame(revs)))
3477                 revs->treesame.name = "treesame";
3478
3479         if (revs->exclude_promisor_objects) {
3480                 for_each_packed_object(mark_uninteresting, revs,
3481                                        FOR_EACH_OBJECT_PROMISOR_ONLY);
3482         }
3483
3484         if (revs->pruning.pathspec.nr == 1 && !revs->reflog_info)
3485                 prepare_to_use_bloom_filter(revs);
3486         if (revs->no_walk != REVISION_WALK_NO_WALK_UNSORTED)
3487                 commit_list_sort_by_date(&revs->commits);
3488         if (revs->no_walk)
3489                 return 0;
3490         if (revs->limited) {
3491                 if (limit_list(revs) < 0)
3492                         return -1;
3493                 if (revs->topo_order)
3494                         sort_in_topological_order(&revs->commits, revs->sort_order);
3495         } else if (revs->topo_order)
3496                 init_topo_walk(revs);
3497         if (revs->line_level_traverse)
3498                 line_log_filter(revs);
3499         if (revs->simplify_merges)
3500                 simplify_merges(revs);
3501         if (revs->children.name)
3502                 set_children(revs);
3503
3504         return 0;
3505 }
3506
3507 static enum rewrite_result rewrite_one_1(struct rev_info *revs,
3508                                          struct commit **pp,
3509                                          struct prio_queue *queue)
3510 {
3511         for (;;) {
3512                 struct commit *p = *pp;
3513                 if (!revs->limited)
3514                         if (process_parents(revs, p, NULL, queue) < 0)
3515                                 return rewrite_one_error;
3516                 if (p->object.flags & UNINTERESTING)
3517                         return rewrite_one_ok;
3518                 if (!(p->object.flags & TREESAME))
3519                         return rewrite_one_ok;
3520                 if (!p->parents)
3521                         return rewrite_one_noparents;
3522                 if ((p = one_relevant_parent(revs, p->parents)) == NULL)
3523                         return rewrite_one_ok;
3524                 *pp = p;
3525         }
3526 }
3527
3528 static void merge_queue_into_list(struct prio_queue *q, struct commit_list **list)
3529 {
3530         while (q->nr) {
3531                 struct commit *item = prio_queue_peek(q);
3532                 struct commit_list *p = *list;
3533
3534                 if (p && p->item->date >= item->date)
3535                         list = &p->next;
3536                 else {
3537                         p = commit_list_insert(item, list);
3538                         list = &p->next; /* skip newly added item */
3539                         prio_queue_get(q); /* pop item */
3540                 }
3541         }
3542 }
3543
3544 static enum rewrite_result rewrite_one(struct rev_info *revs, struct commit **pp)
3545 {
3546         struct prio_queue queue = { compare_commits_by_commit_date };
3547         enum rewrite_result ret = rewrite_one_1(revs, pp, &queue);
3548         merge_queue_into_list(&queue, &revs->commits);
3549         clear_prio_queue(&queue);
3550         return ret;
3551 }
3552
3553 int rewrite_parents(struct rev_info *revs, struct commit *commit,
3554         rewrite_parent_fn_t rewrite_parent)
3555 {
3556         struct commit_list **pp = &commit->parents;
3557         while (*pp) {
3558                 struct commit_list *parent = *pp;
3559                 switch (rewrite_parent(revs, &parent->item)) {
3560                 case rewrite_one_ok:
3561                         break;
3562                 case rewrite_one_noparents:
3563                         *pp = parent->next;
3564                         continue;
3565                 case rewrite_one_error:
3566                         return -1;
3567                 }
3568                 pp = &parent->next;
3569         }
3570         remove_duplicate_parents(revs, commit);
3571         return 0;
3572 }
3573
3574 static int commit_rewrite_person(struct strbuf *buf, const char *what, struct string_list *mailmap)
3575 {
3576         char *person, *endp;
3577         size_t len, namelen, maillen;
3578         const char *name;
3579         const char *mail;
3580         struct ident_split ident;
3581
3582         person = strstr(buf->buf, what);
3583         if (!person)
3584                 return 0;
3585
3586         person += strlen(what);
3587         endp = strchr(person, '\n');
3588         if (!endp)
3589                 return 0;
3590
3591         len = endp - person;
3592
3593         if (split_ident_line(&ident, person, len))
3594                 return 0;
3595
3596         mail = ident.mail_begin;
3597         maillen = ident.mail_end - ident.mail_begin;
3598         name = ident.name_begin;
3599         namelen = ident.name_end - ident.name_begin;
3600
3601         if (map_user(mailmap, &mail, &maillen, &name, &namelen)) {
3602                 struct strbuf namemail = STRBUF_INIT;
3603
3604                 strbuf_addf(&namemail, "%.*s <%.*s>",
3605                             (int)namelen, name, (int)maillen, mail);
3606
3607                 strbuf_splice(buf, ident.name_begin - buf->buf,
3608                               ident.mail_end - ident.name_begin + 1,
3609                               namemail.buf, namemail.len);
3610
3611                 strbuf_release(&namemail);
3612
3613                 return 1;
3614         }
3615
3616         return 0;
3617 }
3618
3619 static int commit_match(struct commit *commit, struct rev_info *opt)
3620 {
3621         int retval;
3622         const char *encoding;
3623         const char *message;
3624         struct strbuf buf = STRBUF_INIT;
3625
3626         if (!opt->grep_filter.pattern_list && !opt->grep_filter.header_list)
3627                 return 1;
3628
3629         /* Prepend "fake" headers as needed */
3630         if (opt->grep_filter.use_reflog_filter) {
3631                 strbuf_addstr(&buf, "reflog ");
3632                 get_reflog_message(&buf, opt->reflog_info);
3633                 strbuf_addch(&buf, '\n');
3634         }
3635
3636         /*
3637          * We grep in the user's output encoding, under the assumption that it
3638          * is the encoding they are most likely to write their grep pattern
3639          * for. In addition, it means we will match the "notes" encoding below,
3640          * so we will not end up with a buffer that has two different encodings
3641          * in it.
3642          */
3643         encoding = get_log_output_encoding();
3644         message = logmsg_reencode(commit, NULL, encoding);
3645
3646         /* Copy the commit to temporary if we are using "fake" headers */
3647         if (buf.len)
3648                 strbuf_addstr(&buf, message);
3649
3650         if (opt->grep_filter.header_list && opt->mailmap) {
3651                 if (!buf.len)
3652                         strbuf_addstr(&buf, message);
3653
3654                 commit_rewrite_person(&buf, "\nauthor ", opt->mailmap);
3655                 commit_rewrite_person(&buf, "\ncommitter ", opt->mailmap);
3656         }
3657
3658         /* Append "fake" message parts as needed */
3659         if (opt->show_notes) {
3660                 if (!buf.len)
3661                         strbuf_addstr(&buf, message);
3662                 format_display_notes(&commit->object.oid, &buf, encoding, 1);
3663         }
3664
3665         /*
3666          * Find either in the original commit message, or in the temporary.
3667          * Note that we cast away the constness of "message" here. It is
3668          * const because it may come from the cached commit buffer. That's OK,
3669          * because we know that it is modifiable heap memory, and that while
3670          * grep_buffer may modify it for speed, it will restore any
3671          * changes before returning.
3672          */
3673         if (buf.len)
3674                 retval = grep_buffer(&opt->grep_filter, buf.buf, buf.len);
3675         else
3676                 retval = grep_buffer(&opt->grep_filter,
3677                                      (char *)message, strlen(message));
3678         strbuf_release(&buf);
3679         unuse_commit_buffer(commit, message);
3680         return opt->invert_grep ? !retval : retval;
3681 }
3682
3683 static inline int want_ancestry(const struct rev_info *revs)
3684 {
3685         return (revs->rewrite_parents || revs->children.name);
3686 }
3687
3688 /*
3689  * Return a timestamp to be used for --since/--until comparisons for this
3690  * commit, based on the revision options.
3691  */
3692 static timestamp_t comparison_date(const struct rev_info *revs,
3693                                    struct commit *commit)
3694 {
3695         return revs->reflog_info ?
3696                 get_reflog_timestamp(revs->reflog_info) :
3697                 commit->date;
3698 }
3699
3700 enum commit_action get_commit_action(struct rev_info *revs, struct commit *commit)
3701 {
3702         if (commit->object.flags & SHOWN)
3703                 return commit_ignore;
3704         if (revs->unpacked && has_object_pack(&commit->object.oid))
3705                 return commit_ignore;
3706         if (commit->object.flags & UNINTERESTING)
3707                 return commit_ignore;
3708         if (revs->min_age != -1 &&
3709             comparison_date(revs, commit) > revs->min_age)
3710                         return commit_ignore;
3711         if (revs->min_parents || (revs->max_parents >= 0)) {
3712                 int n = commit_list_count(commit->parents);
3713                 if ((n < revs->min_parents) ||
3714                     ((revs->max_parents >= 0) && (n > revs->max_parents)))
3715                         return commit_ignore;
3716         }
3717         if (!commit_match(commit, revs))
3718                 return commit_ignore;
3719         if (revs->prune && revs->dense) {
3720                 /* Commit without changes? */
3721                 if (commit->object.flags & TREESAME) {
3722                         int n;
3723                         struct commit_list *p;
3724                         /* drop merges unless we want parenthood */
3725                         if (!want_ancestry(revs))
3726                                 return commit_ignore;
3727                         /*
3728                          * If we want ancestry, then need to keep any merges
3729                          * between relevant commits to tie together topology.
3730                          * For consistency with TREESAME and simplification
3731                          * use "relevant" here rather than just INTERESTING,
3732                          * to treat bottom commit(s) as part of the topology.
3733                          */
3734                         for (n = 0, p = commit->parents; p; p = p->next)
3735                                 if (relevant_commit(p->item))
3736                                         if (++n >= 2)
3737                                                 return commit_show;
3738                         return commit_ignore;
3739                 }
3740         }
3741         return commit_show;
3742 }
3743
3744 define_commit_slab(saved_parents, struct commit_list *);
3745
3746 #define EMPTY_PARENT_LIST ((struct commit_list *)-1)
3747
3748 /*
3749  * You may only call save_parents() once per commit (this is checked
3750  * for non-root commits).
3751  */
3752 static void save_parents(struct rev_info *revs, struct commit *commit)
3753 {
3754         struct commit_list **pp;
3755
3756         if (!revs->saved_parents_slab) {
3757                 revs->saved_parents_slab = xmalloc(sizeof(struct saved_parents));
3758                 init_saved_parents(revs->saved_parents_slab);
3759         }
3760
3761         pp = saved_parents_at(revs->saved_parents_slab, commit);
3762
3763         /*
3764          * When walking with reflogs, we may visit the same commit
3765          * several times: once for each appearance in the reflog.
3766          *
3767          * In this case, save_parents() will be called multiple times.
3768          * We want to keep only the first set of parents.  We need to
3769          * store a sentinel value for an empty (i.e., NULL) parent
3770          * list to distinguish it from a not-yet-saved list, however.
3771          */
3772         if (*pp)
3773                 return;
3774         if (commit->parents)
3775                 *pp = copy_commit_list(commit->parents);
3776         else
3777                 *pp = EMPTY_PARENT_LIST;
3778 }
3779
3780 static void free_saved_parents(struct rev_info *revs)
3781 {
3782         if (revs->saved_parents_slab)
3783                 clear_saved_parents(revs->saved_parents_slab);
3784 }
3785
3786 struct commit_list *get_saved_parents(struct rev_info *revs, const struct commit *commit)
3787 {
3788         struct commit_list *parents;
3789
3790         if (!revs->saved_parents_slab)
3791                 return commit->parents;
3792
3793         parents = *saved_parents_at(revs->saved_parents_slab, commit);
3794         if (parents == EMPTY_PARENT_LIST)
3795                 return NULL;
3796         return parents;
3797 }
3798
3799 enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit)
3800 {
3801         enum commit_action action = get_commit_action(revs, commit);
3802
3803         if (action == commit_show &&
3804             revs->prune && revs->dense && want_ancestry(revs)) {
3805                 /*
3806                  * --full-diff on simplified parents is no good: it
3807                  * will show spurious changes from the commits that
3808                  * were elided.  So we save the parents on the side
3809                  * when --full-diff is in effect.
3810                  */
3811                 if (revs->full_diff)
3812                         save_parents(revs, commit);
3813                 if (rewrite_parents(revs, commit, rewrite_one) < 0)
3814                         return commit_error;
3815         }
3816         return action;
3817 }
3818
3819 static void track_linear(struct rev_info *revs, struct commit *commit)
3820 {
3821         if (revs->track_first_time) {
3822                 revs->linear = 1;
3823                 revs->track_first_time = 0;
3824         } else {
3825                 struct commit_list *p;
3826                 for (p = revs->previous_parents; p; p = p->next)
3827                         if (p->item == NULL || /* first commit */
3828                             oideq(&p->item->object.oid, &commit->object.oid))
3829                                 break;
3830                 revs->linear = p != NULL;
3831         }
3832         if (revs->reverse) {
3833                 if (revs->linear)
3834                         commit->object.flags |= TRACK_LINEAR;
3835         }
3836         free_commit_list(revs->previous_parents);
3837         revs->previous_parents = copy_commit_list(commit->parents);
3838 }
3839
3840 static struct commit *get_revision_1(struct rev_info *revs)
3841 {
3842         while (1) {
3843                 struct commit *commit;
3844
3845                 if (revs->reflog_info)
3846                         commit = next_reflog_entry(revs->reflog_info);
3847                 else if (revs->topo_walk_info)
3848                         commit = next_topo_commit(revs);
3849                 else
3850                         commit = pop_commit(&revs->commits);
3851
3852                 if (!commit)
3853                         return NULL;
3854
3855                 if (revs->reflog_info)
3856                         commit->object.flags &= ~(ADDED | SEEN | SHOWN);
3857
3858                 /*
3859                  * If we haven't done the list limiting, we need to look at
3860                  * the parents here. We also need to do the date-based limiting
3861                  * that we'd otherwise have done in limit_list().
3862                  */
3863                 if (!revs->limited) {
3864                         if (revs->max_age != -1 &&
3865                             comparison_date(revs, commit) < revs->max_age)
3866                                 continue;
3867
3868                         if (revs->reflog_info)
3869                                 try_to_simplify_commit(revs, commit);
3870                         else if (revs->topo_walk_info)
3871                                 expand_topo_walk(revs, commit);
3872                         else if (process_parents(revs, commit, &revs->commits, NULL) < 0) {
3873                                 if (!revs->ignore_missing_links)
3874                                         die("Failed to traverse parents of commit %s",
3875                                                 oid_to_hex(&commit->object.oid));
3876                         }
3877                 }
3878
3879                 switch (simplify_commit(revs, commit)) {
3880                 case commit_ignore:
3881                         continue;
3882                 case commit_error:
3883                         die("Failed to simplify parents of commit %s",
3884                             oid_to_hex(&commit->object.oid));
3885                 default:
3886                         if (revs->track_linear)
3887                                 track_linear(revs, commit);
3888                         return commit;
3889                 }
3890         }
3891 }
3892
3893 /*
3894  * Return true for entries that have not yet been shown.  (This is an
3895  * object_array_each_func_t.)
3896  */
3897 static int entry_unshown(struct object_array_entry *entry, void *cb_data_unused)
3898 {
3899         return !(entry->item->flags & SHOWN);
3900 }
3901
3902 /*
3903  * If array is on the verge of a realloc, garbage-collect any entries
3904  * that have already been shown to try to free up some space.
3905  */
3906 static void gc_boundary(struct object_array *array)
3907 {
3908         if (array->nr == array->alloc)
3909                 object_array_filter(array, entry_unshown, NULL);
3910 }
3911
3912 static void create_boundary_commit_list(struct rev_info *revs)
3913 {
3914         unsigned i;
3915         struct commit *c;
3916         struct object_array *array = &revs->boundary_commits;
3917         struct object_array_entry *objects = array->objects;
3918
3919         /*
3920          * If revs->commits is non-NULL at this point, an error occurred in
3921          * get_revision_1().  Ignore the error and continue printing the
3922          * boundary commits anyway.  (This is what the code has always
3923          * done.)
3924          */
3925         if (revs->commits) {
3926                 free_commit_list(revs->commits);
3927                 revs->commits = NULL;
3928         }
3929
3930         /*
3931          * Put all of the actual boundary commits from revs->boundary_commits
3932          * into revs->commits
3933          */
3934         for (i = 0; i < array->nr; i++) {
3935                 c = (struct commit *)(objects[i].item);
3936                 if (!c)
3937                         continue;
3938                 if (!(c->object.flags & CHILD_SHOWN))
3939                         continue;
3940                 if (c->object.flags & (SHOWN | BOUNDARY))
3941                         continue;
3942                 c->object.flags |= BOUNDARY;
3943                 commit_list_insert(c, &revs->commits);
3944         }
3945
3946         /*
3947          * If revs->topo_order is set, sort the boundary commits
3948          * in topological order
3949          */
3950         sort_in_topological_order(&revs->commits, revs->sort_order);
3951 }
3952
3953 static struct commit *get_revision_internal(struct rev_info *revs)
3954 {
3955         struct commit *c = NULL;
3956         struct commit_list *l;
3957
3958         if (revs->boundary == 2) {
3959                 /*
3960                  * All of the normal commits have already been returned,
3961                  * and we are now returning boundary commits.
3962                  * create_boundary_commit_list() has populated
3963                  * revs->commits with the remaining commits to return.
3964                  */
3965                 c = pop_commit(&revs->commits);
3966                 if (c)
3967                         c->object.flags |= SHOWN;
3968                 return c;
3969         }
3970
3971         /*
3972          * If our max_count counter has reached zero, then we are done. We
3973          * don't simply return NULL because we still might need to show
3974          * boundary commits. But we want to avoid calling get_revision_1, which
3975          * might do a considerable amount of work finding the next commit only
3976          * for us to throw it away.
3977          *
3978          * If it is non-zero, then either we don't have a max_count at all
3979          * (-1), or it is still counting, in which case we decrement.
3980          */
3981         if (revs->max_count) {
3982                 c = get_revision_1(revs);
3983                 if (c) {
3984                         while (revs->skip_count > 0) {
3985                                 revs->skip_count--;
3986                                 c = get_revision_1(revs);
3987                                 if (!c)
3988                                         break;
3989                         }
3990                 }
3991
3992                 if (revs->max_count > 0)
3993                         revs->max_count--;
3994         }
3995
3996         if (c)
3997                 c->object.flags |= SHOWN;
3998
3999         if (!revs->boundary)
4000                 return c;
4001
4002         if (!c) {
4003                 /*
4004                  * get_revision_1() runs out the commits, and
4005                  * we are done computing the boundaries.
4006                  * switch to boundary commits output mode.
4007                  */
4008                 revs->boundary = 2;
4009
4010                 /*
4011                  * Update revs->commits to contain the list of
4012                  * boundary commits.
4013                  */
4014                 create_boundary_commit_list(revs);
4015
4016                 return get_revision_internal(revs);
4017         }
4018
4019         /*
4020          * boundary commits are the commits that are parents of the
4021          * ones we got from get_revision_1() but they themselves are
4022          * not returned from get_revision_1().  Before returning
4023          * 'c', we need to mark its parents that they could be boundaries.
4024          */
4025
4026         for (l = c->parents; l; l = l->next) {
4027                 struct object *p;
4028                 p = &(l->item->object);
4029                 if (p->flags & (CHILD_SHOWN | SHOWN))
4030                         continue;
4031                 p->flags |= CHILD_SHOWN;
4032                 gc_boundary(&revs->boundary_commits);
4033                 add_object_array(p, NULL, &revs->boundary_commits);
4034         }
4035
4036         return c;
4037 }
4038
4039 struct commit *get_revision(struct rev_info *revs)
4040 {
4041         struct commit *c;
4042         struct commit_list *reversed;
4043
4044         if (revs->reverse) {
4045                 reversed = NULL;
4046                 while ((c = get_revision_internal(revs)))
4047                         commit_list_insert(c, &reversed);
4048                 revs->commits = reversed;
4049                 revs->reverse = 0;
4050                 revs->reverse_output_stage = 1;
4051         }
4052
4053         if (revs->reverse_output_stage) {
4054                 c = pop_commit(&revs->commits);
4055                 if (revs->track_linear)
4056                         revs->linear = !!(c && c->object.flags & TRACK_LINEAR);
4057                 return c;
4058         }
4059
4060         c = get_revision_internal(revs);
4061         if (c && revs->graph)
4062                 graph_update(revs->graph, c);
4063         if (!c) {
4064                 free_saved_parents(revs);
4065                 if (revs->previous_parents) {
4066                         free_commit_list(revs->previous_parents);
4067                         revs->previous_parents = NULL;
4068                 }
4069         }
4070         return c;
4071 }
4072
4073 const char *get_revision_mark(const struct rev_info *revs, const struct commit *commit)
4074 {
4075         if (commit->object.flags & BOUNDARY)
4076                 return "-";
4077         else if (commit->object.flags & UNINTERESTING)
4078                 return "^";
4079         else if (commit->object.flags & PATCHSAME)
4080                 return "=";
4081         else if (!revs || revs->left_right) {
4082                 if (commit->object.flags & SYMMETRIC_LEFT)
4083                         return "<";
4084                 else
4085                         return ">";
4086         } else if (revs->graph)
4087                 return "*";
4088         else if (revs->cherry_mark)
4089                 return "+";
4090         return "";
4091 }
4092
4093 void put_revision_mark(const struct rev_info *revs, const struct commit *commit)
4094 {
4095         const char *mark = get_revision_mark(revs, commit);
4096         if (!strlen(mark))
4097                 return;
4098         fputs(mark, stdout);
4099         putchar(' ');
4100 }