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