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