revision: avoid out-of-bounds read/write on empty pathspec
[git] / revision.c
1 #include "cache.h"
2 #include "object-store.h"
3 #include "tag.h"
4 #include "blob.h"
5 #include "tree.h"
6 #include "commit.h"
7 #include "diff.h"
8 #include "refs.h"
9 #include "revision.h"
10 #include "repository.h"
11 #include "graph.h"
12 #include "grep.h"
13 #include "reflog-walk.h"
14 #include "patch-ids.h"
15 #include "decorate.h"
16 #include "log-tree.h"
17 #include "string-list.h"
18 #include "line-log.h"
19 #include "mailmap.h"
20 #include "commit-slab.h"
21 #include "dir.h"
22 #include "cache-tree.h"
23 #include "bisect.h"
24 #include "packfile.h"
25 #include "worktree.h"
26 #include "argv-array.h"
27 #include "commit-reach.h"
28 #include "commit-graph.h"
29 #include "prio-queue.h"
30 #include "hashmap.h"
31 #include "utf8.h"
32 #include "bloom.h"
33 #include "json-writer.h"
34
35 volatile show_early_output_fn_t show_early_output;
36
37 static const char *term_bad;
38 static const char *term_good;
39
40 implement_shared_commit_slab(revision_sources, char *);
41
42 static inline int want_ancestry(const struct rev_info *revs);
43
44 void show_object_with_name(FILE *out, struct object *obj, const char *name)
45 {
46         const char *p;
47
48         fprintf(out, "%s ", oid_to_hex(&obj->oid));
49         for (p = name; *p && *p != '\n'; p++)
50                 fputc(*p, out);
51         fputc('\n', out);
52 }
53
54 static void mark_blob_uninteresting(struct blob *blob)
55 {
56         if (!blob)
57                 return;
58         if (blob->object.flags & UNINTERESTING)
59                 return;
60         blob->object.flags |= UNINTERESTING;
61 }
62
63 static void mark_tree_contents_uninteresting(struct repository *r,
64                                              struct tree *tree)
65 {
66         struct tree_desc desc;
67         struct name_entry entry;
68
69         if (parse_tree_gently(tree, 1) < 0)
70                 return;
71
72         init_tree_desc(&desc, tree->buffer, tree->size);
73         while (tree_entry(&desc, &entry)) {
74                 switch (object_type(entry.mode)) {
75                 case OBJ_TREE:
76                         mark_tree_uninteresting(r, lookup_tree(r, &entry.oid));
77                         break;
78                 case OBJ_BLOB:
79                         mark_blob_uninteresting(lookup_blob(r, &entry.oid));
80                         break;
81                 default:
82                         /* Subproject commit - not in this repository */
83                         break;
84                 }
85         }
86
87         /*
88          * We don't care about the tree any more
89          * after it has been marked uninteresting.
90          */
91         free_tree_buffer(tree);
92 }
93
94 void mark_tree_uninteresting(struct repository *r, struct tree *tree)
95 {
96         struct object *obj;
97
98         if (!tree)
99                 return;
100
101         obj = &tree->object;
102         if (obj->flags & UNINTERESTING)
103                 return;
104         obj->flags |= UNINTERESTING;
105         mark_tree_contents_uninteresting(r, tree);
106 }
107
108 struct path_and_oids_entry {
109         struct hashmap_entry ent;
110         char *path;
111         struct oidset trees;
112 };
113
114 static int path_and_oids_cmp(const void *hashmap_cmp_fn_data,
115                              const struct hashmap_entry *eptr,
116                              const struct hashmap_entry *entry_or_key,
117                              const void *keydata)
118 {
119         const struct path_and_oids_entry *e1, *e2;
120
121         e1 = container_of(eptr, const struct path_and_oids_entry, ent);
122         e2 = container_of(entry_or_key, const struct path_and_oids_entry, ent);
123
124         return strcmp(e1->path, e2->path);
125 }
126
127 static void paths_and_oids_init(struct hashmap *map)
128 {
129         hashmap_init(map, path_and_oids_cmp, NULL, 0);
130 }
131
132 static void paths_and_oids_clear(struct hashmap *map)
133 {
134         struct hashmap_iter iter;
135         struct path_and_oids_entry *entry;
136
137         hashmap_for_each_entry(map, &iter, entry, ent /* member name */) {
138                 oidset_clear(&entry->trees);
139                 free(entry->path);
140         }
141
142         hashmap_free_entries(map, struct path_and_oids_entry, ent);
143 }
144
145 static void paths_and_oids_insert(struct hashmap *map,
146                                   const char *path,
147                                   const struct object_id *oid)
148 {
149         int hash = strhash(path);
150         struct path_and_oids_entry key;
151         struct path_and_oids_entry *entry;
152
153         hashmap_entry_init(&key.ent, hash);
154
155         /* use a shallow copy for the lookup */
156         key.path = (char *)path;
157         oidset_init(&key.trees, 0);
158
159         entry = hashmap_get_entry(map, &key, ent, NULL);
160         if (!entry) {
161                 entry = xcalloc(1, sizeof(struct path_and_oids_entry));
162                 hashmap_entry_init(&entry->ent, hash);
163                 entry->path = xstrdup(key.path);
164                 oidset_init(&entry->trees, 16);
165                 hashmap_put(map, &entry->ent);
166         }
167
168         oidset_insert(&entry->trees, oid);
169 }
170
171 static void add_children_by_path(struct repository *r,
172                                  struct tree *tree,
173                                  struct hashmap *map)
174 {
175         struct tree_desc desc;
176         struct name_entry entry;
177
178         if (!tree)
179                 return;
180
181         if (parse_tree_gently(tree, 1) < 0)
182                 return;
183
184         init_tree_desc(&desc, tree->buffer, tree->size);
185         while (tree_entry(&desc, &entry)) {
186                 switch (object_type(entry.mode)) {
187                 case OBJ_TREE:
188                         paths_and_oids_insert(map, entry.path, &entry.oid);
189
190                         if (tree->object.flags & UNINTERESTING) {
191                                 struct tree *child = lookup_tree(r, &entry.oid);
192                                 if (child)
193                                         child->object.flags |= UNINTERESTING;
194                         }
195                         break;
196                 case OBJ_BLOB:
197                         if (tree->object.flags & UNINTERESTING) {
198                                 struct blob *child = lookup_blob(r, &entry.oid);
199                                 if (child)
200                                         child->object.flags |= UNINTERESTING;
201                         }
202                         break;
203                 default:
204                         /* Subproject commit - not in this repository */
205                         break;
206                 }
207         }
208
209         free_tree_buffer(tree);
210 }
211
212 void mark_trees_uninteresting_sparse(struct repository *r,
213                                      struct oidset *trees)
214 {
215         unsigned has_interesting = 0, has_uninteresting = 0;
216         struct hashmap map;
217         struct hashmap_iter map_iter;
218         struct path_and_oids_entry *entry;
219         struct object_id *oid;
220         struct oidset_iter iter;
221
222         oidset_iter_init(trees, &iter);
223         while ((!has_interesting || !has_uninteresting) &&
224                (oid = oidset_iter_next(&iter))) {
225                 struct tree *tree = lookup_tree(r, oid);
226
227                 if (!tree)
228                         continue;
229
230                 if (tree->object.flags & UNINTERESTING)
231                         has_uninteresting = 1;
232                 else
233                         has_interesting = 1;
234         }
235
236         /* Do not walk unless we have both types of trees. */
237         if (!has_uninteresting || !has_interesting)
238                 return;
239
240         paths_and_oids_init(&map);
241
242         oidset_iter_init(trees, &iter);
243         while ((oid = oidset_iter_next(&iter))) {
244                 struct tree *tree = lookup_tree(r, oid);
245                 add_children_by_path(r, tree, &map);
246         }
247
248         hashmap_for_each_entry(&map, &map_iter, entry, ent /* member name */)
249                 mark_trees_uninteresting_sparse(r, &entry->trees);
250
251         paths_and_oids_clear(&map);
252 }
253
254 struct commit_stack {
255         struct commit **items;
256         size_t nr, alloc;
257 };
258 #define COMMIT_STACK_INIT { NULL, 0, 0 }
259
260 static void commit_stack_push(struct commit_stack *stack, struct commit *commit)
261 {
262         ALLOC_GROW(stack->items, stack->nr + 1, stack->alloc);
263         stack->items[stack->nr++] = commit;
264 }
265
266 static struct commit *commit_stack_pop(struct commit_stack *stack)
267 {
268         return stack->nr ? stack->items[--stack->nr] : NULL;
269 }
270
271 static void commit_stack_clear(struct commit_stack *stack)
272 {
273         FREE_AND_NULL(stack->items);
274         stack->nr = stack->alloc = 0;
275 }
276
277 static void mark_one_parent_uninteresting(struct commit *commit,
278                                           struct commit_stack *pending)
279 {
280         struct commit_list *l;
281
282         if (commit->object.flags & UNINTERESTING)
283                 return;
284         commit->object.flags |= UNINTERESTING;
285
286         /*
287          * Normally we haven't parsed the parent
288          * yet, so we won't have a parent of a parent
289          * here. However, it may turn out that we've
290          * reached this commit some other way (where it
291          * wasn't uninteresting), in which case we need
292          * to mark its parents recursively too..
293          */
294         for (l = commit->parents; l; l = l->next)
295                 commit_stack_push(pending, l->item);
296 }
297
298 void mark_parents_uninteresting(struct commit *commit)
299 {
300         struct commit_stack pending = COMMIT_STACK_INIT;
301         struct commit_list *l;
302
303         for (l = commit->parents; l; l = l->next)
304                 mark_one_parent_uninteresting(l->item, &pending);
305
306         while (pending.nr > 0)
307                 mark_one_parent_uninteresting(commit_stack_pop(&pending),
308                                               &pending);
309
310         commit_stack_clear(&pending);
311 }
312
313 static void add_pending_object_with_path(struct rev_info *revs,
314                                          struct object *obj,
315                                          const char *name, unsigned mode,
316                                          const char *path)
317 {
318         if (!obj)
319                 return;
320         if (revs->no_walk && (obj->flags & UNINTERESTING))
321                 revs->no_walk = 0;
322         if (revs->reflog_info && obj->type == OBJ_COMMIT) {
323                 struct strbuf buf = STRBUF_INIT;
324                 int len = interpret_branch_name(name, 0, &buf, 0);
325
326                 if (0 < len && name[len] && buf.len)
327                         strbuf_addstr(&buf, name + len);
328                 add_reflog_for_walk(revs->reflog_info,
329                                     (struct commit *)obj,
330                                     buf.buf[0] ? buf.buf: name);
331                 strbuf_release(&buf);
332                 return; /* do not add the commit itself */
333         }
334         add_object_array_with_path(obj, name, &revs->pending, mode, path);
335 }
336
337 static void add_pending_object_with_mode(struct rev_info *revs,
338                                          struct object *obj,
339                                          const char *name, unsigned mode)
340 {
341         add_pending_object_with_path(revs, obj, name, mode, NULL);
342 }
343
344 void add_pending_object(struct rev_info *revs,
345                         struct object *obj, const char *name)
346 {
347         add_pending_object_with_mode(revs, obj, name, S_IFINVALID);
348 }
349
350 void add_head_to_pending(struct rev_info *revs)
351 {
352         struct object_id oid;
353         struct object *obj;
354         if (get_oid("HEAD", &oid))
355                 return;
356         obj = parse_object(revs->repo, &oid);
357         if (!obj)
358                 return;
359         add_pending_object(revs, obj, "HEAD");
360 }
361
362 static struct object *get_reference(struct rev_info *revs, const char *name,
363                                     const struct object_id *oid,
364                                     unsigned int flags)
365 {
366         struct object *object;
367
368         /*
369          * If the repository has commit graphs, repo_parse_commit() avoids
370          * reading the object buffer, so use it whenever possible.
371          */
372         if (oid_object_info(revs->repo, oid, NULL) == OBJ_COMMIT) {
373                 struct commit *c = lookup_commit(revs->repo, oid);
374                 if (!repo_parse_commit(revs->repo, c))
375                         object = (struct object *) c;
376                 else
377                         object = NULL;
378         } else {
379                 object = parse_object(revs->repo, oid);
380         }
381
382         if (!object) {
383                 if (revs->ignore_missing)
384                         return object;
385                 if (revs->exclude_promisor_objects && is_promisor_object(oid))
386                         return NULL;
387                 die("bad object %s", name);
388         }
389         object->flags |= flags;
390         return object;
391 }
392
393 void add_pending_oid(struct rev_info *revs, const char *name,
394                       const struct object_id *oid, unsigned int flags)
395 {
396         struct object *object = get_reference(revs, name, oid, flags);
397         add_pending_object(revs, object, name);
398 }
399
400 static struct commit *handle_commit(struct rev_info *revs,
401                                     struct object_array_entry *entry)
402 {
403         struct object *object = entry->item;
404         const char *name = entry->name;
405         const char *path = entry->path;
406         unsigned int mode = entry->mode;
407         unsigned long flags = object->flags;
408
409         /*
410          * Tag object? Look what it points to..
411          */
412         while (object->type == OBJ_TAG) {
413                 struct tag *tag = (struct tag *) object;
414                 if (revs->tag_objects && !(flags & UNINTERESTING))
415                         add_pending_object(revs, object, tag->tag);
416                 object = parse_object(revs->repo, get_tagged_oid(tag));
417                 if (!object) {
418                         if (revs->ignore_missing_links || (flags & UNINTERESTING))
419                                 return NULL;
420                         if (revs->exclude_promisor_objects &&
421                             is_promisor_object(&tag->tagged->oid))
422                                 return NULL;
423                         die("bad object %s", oid_to_hex(&tag->tagged->oid));
424                 }
425                 object->flags |= flags;
426                 /*
427                  * We'll handle the tagged object by looping or dropping
428                  * through to the non-tag handlers below. Do not
429                  * propagate path data from the tag's pending entry.
430                  */
431                 path = NULL;
432                 mode = 0;
433         }
434
435         /*
436          * Commit object? Just return it, we'll do all the complex
437          * reachability crud.
438          */
439         if (object->type == OBJ_COMMIT) {
440                 struct commit *commit = (struct commit *)object;
441
442                 if (parse_commit(commit) < 0)
443                         die("unable to parse commit %s", name);
444                 if (flags & UNINTERESTING) {
445                         mark_parents_uninteresting(commit);
446
447                         if (!revs->topo_order || !generation_numbers_enabled(the_repository))
448                                 revs->limited = 1;
449                 }
450                 if (revs->sources) {
451                         char **slot = revision_sources_at(revs->sources, commit);
452
453                         if (!*slot)
454                                 *slot = xstrdup(name);
455                 }
456                 return commit;
457         }
458
459         /*
460          * Tree object? Either mark it uninteresting, or add it
461          * to the list of objects to look at later..
462          */
463         if (object->type == OBJ_TREE) {
464                 struct tree *tree = (struct tree *)object;
465                 if (!revs->tree_objects)
466                         return NULL;
467                 if (flags & UNINTERESTING) {
468                         mark_tree_contents_uninteresting(revs->repo, tree);
469                         return NULL;
470                 }
471                 add_pending_object_with_path(revs, object, name, mode, path);
472                 return NULL;
473         }
474
475         /*
476          * Blob object? You know the drill by now..
477          */
478         if (object->type == OBJ_BLOB) {
479                 if (!revs->blob_objects)
480                         return NULL;
481                 if (flags & UNINTERESTING)
482                         return NULL;
483                 add_pending_object_with_path(revs, object, name, mode, path);
484                 return NULL;
485         }
486         die("%s is unknown object", name);
487 }
488
489 static int everybody_uninteresting(struct commit_list *orig,
490                                    struct commit **interesting_cache)
491 {
492         struct commit_list *list = orig;
493
494         if (*interesting_cache) {
495                 struct commit *commit = *interesting_cache;
496                 if (!(commit->object.flags & UNINTERESTING))
497                         return 0;
498         }
499
500         while (list) {
501                 struct commit *commit = list->item;
502                 list = list->next;
503                 if (commit->object.flags & UNINTERESTING)
504                         continue;
505
506                 *interesting_cache = commit;
507                 return 0;
508         }
509         return 1;
510 }
511
512 /*
513  * A definition of "relevant" commit that we can use to simplify limited graphs
514  * by eliminating side branches.
515  *
516  * A "relevant" commit is one that is !UNINTERESTING (ie we are including it
517  * in our list), or that is a specified BOTTOM commit. Then after computing
518  * a limited list, during processing we can generally ignore boundary merges
519  * coming from outside the graph, (ie from irrelevant parents), and treat
520  * those merges as if they were single-parent. TREESAME is defined to consider
521  * only relevant parents, if any. If we are TREESAME to our on-graph parents,
522  * we don't care if we were !TREESAME to non-graph parents.
523  *
524  * Treating bottom commits as relevant ensures that a limited graph's
525  * connection to the actual bottom commit is not viewed as a side branch, but
526  * treated as part of the graph. For example:
527  *
528  *   ....Z...A---X---o---o---B
529  *        .     /
530  *         W---Y
531  *
532  * When computing "A..B", the A-X connection is at least as important as
533  * Y-X, despite A being flagged UNINTERESTING.
534  *
535  * And when computing --ancestry-path "A..B", the A-X connection is more
536  * important than Y-X, despite both A and Y being flagged UNINTERESTING.
537  */
538 static inline int relevant_commit(struct commit *commit)
539 {
540         return (commit->object.flags & (UNINTERESTING | BOTTOM)) != UNINTERESTING;
541 }
542
543 /*
544  * Return a single relevant commit from a parent list. If we are a TREESAME
545  * commit, and this selects one of our parents, then we can safely simplify to
546  * that parent.
547  */
548 static struct commit *one_relevant_parent(const struct rev_info *revs,
549                                           struct commit_list *orig)
550 {
551         struct commit_list *list = orig;
552         struct commit *relevant = NULL;
553
554         if (!orig)
555                 return NULL;
556
557         /*
558          * For 1-parent commits, or if first-parent-only, then return that
559          * first parent (even if not "relevant" by the above definition).
560          * TREESAME will have been set purely on that parent.
561          */
562         if (revs->first_parent_only || !orig->next)
563                 return orig->item;
564
565         /*
566          * For multi-parent commits, identify a sole relevant parent, if any.
567          * If we have only one relevant parent, then TREESAME will be set purely
568          * with regard to that parent, and we can simplify accordingly.
569          *
570          * If we have more than one relevant parent, or no relevant parents
571          * (and multiple irrelevant ones), then we can't select a parent here
572          * and return NULL.
573          */
574         while (list) {
575                 struct commit *commit = list->item;
576                 list = list->next;
577                 if (relevant_commit(commit)) {
578                         if (relevant)
579                                 return NULL;
580                         relevant = commit;
581                 }
582         }
583         return relevant;
584 }
585
586 /*
587  * The goal is to get REV_TREE_NEW as the result only if the
588  * diff consists of all '+' (and no other changes), REV_TREE_OLD
589  * if the whole diff is removal of old data, and otherwise
590  * REV_TREE_DIFFERENT (of course if the trees are the same we
591  * want REV_TREE_SAME).
592  *
593  * The only time we care about the distinction is when
594  * remove_empty_trees is in effect, in which case we care only about
595  * whether the whole change is REV_TREE_NEW, or if there's another type
596  * of change. Which means we can stop the diff early in either of these
597  * cases:
598  *
599  *   1. We're not using remove_empty_trees at all.
600  *
601  *   2. We saw anything except REV_TREE_NEW.
602  */
603 static int tree_difference = REV_TREE_SAME;
604
605 static void file_add_remove(struct diff_options *options,
606                     int addremove, unsigned mode,
607                     const struct object_id *oid,
608                     int oid_valid,
609                     const char *fullpath, unsigned dirty_submodule)
610 {
611         int diff = addremove == '+' ? REV_TREE_NEW : REV_TREE_OLD;
612         struct rev_info *revs = options->change_fn_data;
613
614         tree_difference |= diff;
615         if (!revs->remove_empty_trees || tree_difference != REV_TREE_NEW)
616                 options->flags.has_changes = 1;
617 }
618
619 static void file_change(struct diff_options *options,
620                  unsigned old_mode, unsigned new_mode,
621                  const struct object_id *old_oid,
622                  const struct object_id *new_oid,
623                  int old_oid_valid, int new_oid_valid,
624                  const char *fullpath,
625                  unsigned old_dirty_submodule, unsigned new_dirty_submodule)
626 {
627         tree_difference = REV_TREE_DIFFERENT;
628         options->flags.has_changes = 1;
629 }
630
631 static int bloom_filter_atexit_registered;
632 static unsigned int count_bloom_filter_maybe;
633 static unsigned int count_bloom_filter_definitely_not;
634 static unsigned int count_bloom_filter_false_positive;
635 static unsigned int count_bloom_filter_not_present;
636
637 static void trace2_bloom_filter_statistics_atexit(void)
638 {
639         struct json_writer jw = JSON_WRITER_INIT;
640
641         jw_object_begin(&jw, 0);
642         jw_object_intmax(&jw, "filter_not_present", count_bloom_filter_not_present);
643         jw_object_intmax(&jw, "maybe", count_bloom_filter_maybe);
644         jw_object_intmax(&jw, "definitely_not", count_bloom_filter_definitely_not);
645         jw_object_intmax(&jw, "false_positive", count_bloom_filter_false_positive);
646         jw_end(&jw);
647
648         trace2_data_json("bloom", the_repository, "statistics", &jw);
649
650         jw_release(&jw);
651 }
652
653 static int forbid_bloom_filters(struct pathspec *spec)
654 {
655         if (spec->has_wildcard)
656                 return 1;
657         if (spec->nr > 1)
658                 return 1;
659         if (spec->magic & ~PATHSPEC_LITERAL)
660                 return 1;
661         if (spec->nr && (spec->items[0].magic & ~PATHSPEC_LITERAL))
662                 return 1;
663
664         return 0;
665 }
666
667 static void prepare_to_use_bloom_filter(struct rev_info *revs)
668 {
669         struct pathspec_item *pi;
670         char *path_alloc = NULL;
671         const char *path, *p;
672         size_t len;
673         int path_component_nr = 1;
674
675         if (!revs->commits)
676                 return;
677
678         if (forbid_bloom_filters(&revs->prune_data))
679                 return;
680
681         repo_parse_commit(revs->repo, revs->commits->item);
682
683         if (!revs->repo->objects->commit_graph)
684                 return;
685
686         revs->bloom_filter_settings = revs->repo->objects->commit_graph->bloom_filter_settings;
687         if (!revs->bloom_filter_settings)
688                 return;
689
690         if (!revs->pruning.pathspec.nr)
691                 return;
692
693         pi = &revs->pruning.pathspec.items[0];
694
695         /* remove single trailing slash from path, if needed */
696         if (pi->len > 0 && pi->match[pi->len - 1] == '/') {
697                 path_alloc = xmemdupz(pi->match, pi->len - 1);
698                 path = path_alloc;
699         } else
700                 path = pi->match;
701
702         len = strlen(path);
703         if (!len) {
704                 revs->bloom_filter_settings = NULL;
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, 0);
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 (parse_commit(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 (parse_commit(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 (parse_commit_gently(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 (parse_commit_gently(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->ignore_merges = 1;
1818         revs->simplify_history = 1;
1819         revs->pruning.repo = r;
1820         revs->pruning.flags.recursive = 1;
1821         revs->pruning.flags.quick = 1;
1822         revs->pruning.add_remove = file_add_remove;
1823         revs->pruning.change = file_change;
1824         revs->pruning.change_fn_data = revs;
1825         revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
1826         revs->dense = 1;
1827         revs->prefix = prefix;
1828         revs->max_age = -1;
1829         revs->min_age = -1;
1830         revs->skip_count = -1;
1831         revs->max_count = -1;
1832         revs->max_parents = -1;
1833         revs->expand_tabs_in_log = -1;
1834
1835         revs->commit_format = CMIT_FMT_DEFAULT;
1836         revs->expand_tabs_in_log_default = 8;
1837
1838         init_grep_defaults(revs->repo);
1839         grep_init(&revs->grep_filter, revs->repo, prefix);
1840         revs->grep_filter.status_only = 1;
1841
1842         repo_diff_setup(revs->repo, &revs->diffopt);
1843         if (prefix && !revs->diffopt.prefix) {
1844                 revs->diffopt.prefix = prefix;
1845                 revs->diffopt.prefix_length = strlen(prefix);
1846         }
1847
1848         init_display_notes(&revs->notes_opt);
1849 }
1850
1851 static void add_pending_commit_list(struct rev_info *revs,
1852                                     struct commit_list *commit_list,
1853                                     unsigned int flags)
1854 {
1855         while (commit_list) {
1856                 struct object *object = &commit_list->item->object;
1857                 object->flags |= flags;
1858                 add_pending_object(revs, object, oid_to_hex(&object->oid));
1859                 commit_list = commit_list->next;
1860         }
1861 }
1862
1863 static void prepare_show_merge(struct rev_info *revs)
1864 {
1865         struct commit_list *bases;
1866         struct commit *head, *other;
1867         struct object_id oid;
1868         const char **prune = NULL;
1869         int i, prune_num = 1; /* counting terminating NULL */
1870         struct index_state *istate = revs->repo->index;
1871
1872         if (get_oid("HEAD", &oid))
1873                 die("--merge without HEAD?");
1874         head = lookup_commit_or_die(&oid, "HEAD");
1875         if (get_oid("MERGE_HEAD", &oid))
1876                 die("--merge without MERGE_HEAD?");
1877         other = lookup_commit_or_die(&oid, "MERGE_HEAD");
1878         add_pending_object(revs, &head->object, "HEAD");
1879         add_pending_object(revs, &other->object, "MERGE_HEAD");
1880         bases = get_merge_bases(head, other);
1881         add_rev_cmdline_list(revs, bases, REV_CMD_MERGE_BASE, UNINTERESTING | BOTTOM);
1882         add_pending_commit_list(revs, bases, UNINTERESTING | BOTTOM);
1883         free_commit_list(bases);
1884         head->object.flags |= SYMMETRIC_LEFT;
1885
1886         if (!istate->cache_nr)
1887                 repo_read_index(revs->repo);
1888         for (i = 0; i < istate->cache_nr; i++) {
1889                 const struct cache_entry *ce = istate->cache[i];
1890                 if (!ce_stage(ce))
1891                         continue;
1892                 if (ce_path_match(istate, ce, &revs->prune_data, NULL)) {
1893                         prune_num++;
1894                         REALLOC_ARRAY(prune, prune_num);
1895                         prune[prune_num-2] = ce->name;
1896                         prune[prune_num-1] = NULL;
1897                 }
1898                 while ((i+1 < istate->cache_nr) &&
1899                        ce_same_name(ce, istate->cache[i+1]))
1900                         i++;
1901         }
1902         clear_pathspec(&revs->prune_data);
1903         parse_pathspec(&revs->prune_data, PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1904                        PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH, "", prune);
1905         revs->limited = 1;
1906 }
1907
1908 static int dotdot_missing(const char *arg, char *dotdot,
1909                           struct rev_info *revs, int symmetric)
1910 {
1911         if (revs->ignore_missing)
1912                 return 0;
1913         /* de-munge so we report the full argument */
1914         *dotdot = '.';
1915         die(symmetric
1916             ? "Invalid symmetric difference expression %s"
1917             : "Invalid revision range %s", arg);
1918 }
1919
1920 static int handle_dotdot_1(const char *arg, char *dotdot,
1921                            struct rev_info *revs, int flags,
1922                            int cant_be_filename,
1923                            struct object_context *a_oc,
1924                            struct object_context *b_oc)
1925 {
1926         const char *a_name, *b_name;
1927         struct object_id a_oid, b_oid;
1928         struct object *a_obj, *b_obj;
1929         unsigned int a_flags, b_flags;
1930         int symmetric = 0;
1931         unsigned int flags_exclude = flags ^ (UNINTERESTING | BOTTOM);
1932         unsigned int oc_flags = GET_OID_COMMITTISH | GET_OID_RECORD_PATH;
1933
1934         a_name = arg;
1935         if (!*a_name)
1936                 a_name = "HEAD";
1937
1938         b_name = dotdot + 2;
1939         if (*b_name == '.') {
1940                 symmetric = 1;
1941                 b_name++;
1942         }
1943         if (!*b_name)
1944                 b_name = "HEAD";
1945
1946         if (get_oid_with_context(revs->repo, a_name, oc_flags, &a_oid, a_oc) ||
1947             get_oid_with_context(revs->repo, b_name, oc_flags, &b_oid, b_oc))
1948                 return -1;
1949
1950         if (!cant_be_filename) {
1951                 *dotdot = '.';
1952                 verify_non_filename(revs->prefix, arg);
1953                 *dotdot = '\0';
1954         }
1955
1956         a_obj = parse_object(revs->repo, &a_oid);
1957         b_obj = parse_object(revs->repo, &b_oid);
1958         if (!a_obj || !b_obj)
1959                 return dotdot_missing(arg, dotdot, revs, symmetric);
1960
1961         if (!symmetric) {
1962                 /* just A..B */
1963                 b_flags = flags;
1964                 a_flags = flags_exclude;
1965         } else {
1966                 /* A...B -- find merge bases between the two */
1967                 struct commit *a, *b;
1968                 struct commit_list *exclude;
1969
1970                 a = lookup_commit_reference(revs->repo, &a_obj->oid);
1971                 b = lookup_commit_reference(revs->repo, &b_obj->oid);
1972                 if (!a || !b)
1973                         return dotdot_missing(arg, dotdot, revs, symmetric);
1974
1975                 exclude = get_merge_bases(a, b);
1976                 add_rev_cmdline_list(revs, exclude, REV_CMD_MERGE_BASE,
1977                                      flags_exclude);
1978                 add_pending_commit_list(revs, exclude, flags_exclude);
1979                 free_commit_list(exclude);
1980
1981                 b_flags = flags;
1982                 a_flags = flags | SYMMETRIC_LEFT;
1983         }
1984
1985         a_obj->flags |= a_flags;
1986         b_obj->flags |= b_flags;
1987         add_rev_cmdline(revs, a_obj, a_name, REV_CMD_LEFT, a_flags);
1988         add_rev_cmdline(revs, b_obj, b_name, REV_CMD_RIGHT, b_flags);
1989         add_pending_object_with_path(revs, a_obj, a_name, a_oc->mode, a_oc->path);
1990         add_pending_object_with_path(revs, b_obj, b_name, b_oc->mode, b_oc->path);
1991         return 0;
1992 }
1993
1994 static int handle_dotdot(const char *arg,
1995                          struct rev_info *revs, int flags,
1996                          int cant_be_filename)
1997 {
1998         struct object_context a_oc, b_oc;
1999         char *dotdot = strstr(arg, "..");
2000         int ret;
2001
2002         if (!dotdot)
2003                 return -1;
2004
2005         memset(&a_oc, 0, sizeof(a_oc));
2006         memset(&b_oc, 0, sizeof(b_oc));
2007
2008         *dotdot = '\0';
2009         ret = handle_dotdot_1(arg, dotdot, revs, flags, cant_be_filename,
2010                               &a_oc, &b_oc);
2011         *dotdot = '.';
2012
2013         free(a_oc.path);
2014         free(b_oc.path);
2015
2016         return ret;
2017 }
2018
2019 int handle_revision_arg(const char *arg_, struct rev_info *revs, int flags, unsigned revarg_opt)
2020 {
2021         struct object_context oc;
2022         char *mark;
2023         struct object *object;
2024         struct object_id oid;
2025         int local_flags;
2026         const char *arg = arg_;
2027         int cant_be_filename = revarg_opt & REVARG_CANNOT_BE_FILENAME;
2028         unsigned get_sha1_flags = GET_OID_RECORD_PATH;
2029
2030         flags = flags & UNINTERESTING ? flags | BOTTOM : flags & ~BOTTOM;
2031
2032         if (!cant_be_filename && !strcmp(arg, "..")) {
2033                 /*
2034                  * Just ".."?  That is not a range but the
2035                  * pathspec for the parent directory.
2036                  */
2037                 return -1;
2038         }
2039
2040         if (!handle_dotdot(arg, revs, flags, revarg_opt))
2041                 return 0;
2042
2043         mark = strstr(arg, "^@");
2044         if (mark && !mark[2]) {
2045                 *mark = 0;
2046                 if (add_parents_only(revs, arg, flags, 0))
2047                         return 0;
2048                 *mark = '^';
2049         }
2050         mark = strstr(arg, "^!");
2051         if (mark && !mark[2]) {
2052                 *mark = 0;
2053                 if (!add_parents_only(revs, arg, flags ^ (UNINTERESTING | BOTTOM), 0))
2054                         *mark = '^';
2055         }
2056         mark = strstr(arg, "^-");
2057         if (mark) {
2058                 int exclude_parent = 1;
2059
2060                 if (mark[2]) {
2061                         char *end;
2062                         exclude_parent = strtoul(mark + 2, &end, 10);
2063                         if (*end != '\0' || !exclude_parent)
2064                                 return -1;
2065                 }
2066
2067                 *mark = 0;
2068                 if (!add_parents_only(revs, arg, flags ^ (UNINTERESTING | BOTTOM), exclude_parent))
2069                         *mark = '^';
2070         }
2071
2072         local_flags = 0;
2073         if (*arg == '^') {
2074                 local_flags = UNINTERESTING | BOTTOM;
2075                 arg++;
2076         }
2077
2078         if (revarg_opt & REVARG_COMMITTISH)
2079                 get_sha1_flags |= GET_OID_COMMITTISH;
2080
2081         if (get_oid_with_context(revs->repo, arg, get_sha1_flags, &oid, &oc))
2082                 return revs->ignore_missing ? 0 : -1;
2083         if (!cant_be_filename)
2084                 verify_non_filename(revs->prefix, arg);
2085         object = get_reference(revs, arg, &oid, flags ^ local_flags);
2086         if (!object)
2087                 return revs->ignore_missing ? 0 : -1;
2088         add_rev_cmdline(revs, object, arg_, REV_CMD_REV, flags ^ local_flags);
2089         add_pending_object_with_path(revs, object, arg, oc.mode, oc.path);
2090         free(oc.path);
2091         return 0;
2092 }
2093
2094 static void read_pathspec_from_stdin(struct strbuf *sb,
2095                                      struct argv_array *prune)
2096 {
2097         while (strbuf_getline(sb, stdin) != EOF)
2098                 argv_array_push(prune, sb->buf);
2099 }
2100
2101 static void read_revisions_from_stdin(struct rev_info *revs,
2102                                       struct argv_array *prune)
2103 {
2104         struct strbuf sb;
2105         int seen_dashdash = 0;
2106         int save_warning;
2107
2108         save_warning = warn_on_object_refname_ambiguity;
2109         warn_on_object_refname_ambiguity = 0;
2110
2111         strbuf_init(&sb, 1000);
2112         while (strbuf_getline(&sb, stdin) != EOF) {
2113                 int len = sb.len;
2114                 if (!len)
2115                         break;
2116                 if (sb.buf[0] == '-') {
2117                         if (len == 2 && sb.buf[1] == '-') {
2118                                 seen_dashdash = 1;
2119                                 break;
2120                         }
2121                         die("options not supported in --stdin mode");
2122                 }
2123                 if (handle_revision_arg(sb.buf, revs, 0,
2124                                         REVARG_CANNOT_BE_FILENAME))
2125                         die("bad revision '%s'", sb.buf);
2126         }
2127         if (seen_dashdash)
2128                 read_pathspec_from_stdin(&sb, prune);
2129
2130         strbuf_release(&sb);
2131         warn_on_object_refname_ambiguity = save_warning;
2132 }
2133
2134 static void add_grep(struct rev_info *revs, const char *ptn, enum grep_pat_token what)
2135 {
2136         append_grep_pattern(&revs->grep_filter, ptn, "command line", 0, what);
2137 }
2138
2139 static void add_header_grep(struct rev_info *revs, enum grep_header_field field, const char *pattern)
2140 {
2141         append_header_grep_pattern(&revs->grep_filter, field, pattern);
2142 }
2143
2144 static void add_message_grep(struct rev_info *revs, const char *pattern)
2145 {
2146         add_grep(revs, pattern, GREP_PATTERN_BODY);
2147 }
2148
2149 static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv,
2150                                int *unkc, const char **unkv,
2151                                const struct setup_revision_opt* opt)
2152 {
2153         const char *arg = argv[0];
2154         const char *optarg;
2155         int argcount;
2156         const unsigned hexsz = the_hash_algo->hexsz;
2157
2158         /* pseudo revision arguments */
2159         if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") ||
2160             !strcmp(arg, "--tags") || !strcmp(arg, "--remotes") ||
2161             !strcmp(arg, "--reflog") || !strcmp(arg, "--not") ||
2162             !strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk") ||
2163             !strcmp(arg, "--bisect") || starts_with(arg, "--glob=") ||
2164             !strcmp(arg, "--indexed-objects") ||
2165             !strcmp(arg, "--alternate-refs") ||
2166             starts_with(arg, "--exclude=") ||
2167             starts_with(arg, "--branches=") || starts_with(arg, "--tags=") ||
2168             starts_with(arg, "--remotes=") || starts_with(arg, "--no-walk="))
2169         {
2170                 unkv[(*unkc)++] = arg;
2171                 return 1;
2172         }
2173
2174         if ((argcount = parse_long_opt("max-count", argv, &optarg))) {
2175                 revs->max_count = atoi(optarg);
2176                 revs->no_walk = 0;
2177                 return argcount;
2178         } else if ((argcount = parse_long_opt("skip", argv, &optarg))) {
2179                 revs->skip_count = atoi(optarg);
2180                 return argcount;
2181         } else if ((*arg == '-') && isdigit(arg[1])) {
2182                 /* accept -<digit>, like traditional "head" */
2183                 if (strtol_i(arg + 1, 10, &revs->max_count) < 0 ||
2184                     revs->max_count < 0)
2185                         die("'%s': not a non-negative integer", arg + 1);
2186                 revs->no_walk = 0;
2187         } else if (!strcmp(arg, "-n")) {
2188                 if (argc <= 1)
2189                         return error("-n requires an argument");
2190                 revs->max_count = atoi(argv[1]);
2191                 revs->no_walk = 0;
2192                 return 2;
2193         } else if (skip_prefix(arg, "-n", &optarg)) {
2194                 revs->max_count = atoi(optarg);
2195                 revs->no_walk = 0;
2196         } else if ((argcount = parse_long_opt("max-age", argv, &optarg))) {
2197                 revs->max_age = atoi(optarg);
2198                 return argcount;
2199         } else if ((argcount = parse_long_opt("since", argv, &optarg))) {
2200                 revs->max_age = approxidate(optarg);
2201                 return argcount;
2202         } else if ((argcount = parse_long_opt("after", argv, &optarg))) {
2203                 revs->max_age = approxidate(optarg);
2204                 return argcount;
2205         } else if ((argcount = parse_long_opt("min-age", argv, &optarg))) {
2206                 revs->min_age = atoi(optarg);
2207                 return argcount;
2208         } else if ((argcount = parse_long_opt("before", argv, &optarg))) {
2209                 revs->min_age = approxidate(optarg);
2210                 return argcount;
2211         } else if ((argcount = parse_long_opt("until", argv, &optarg))) {
2212                 revs->min_age = approxidate(optarg);
2213                 return argcount;
2214         } else if (!strcmp(arg, "--first-parent")) {
2215                 revs->first_parent_only = 1;
2216         } else if (!strcmp(arg, "--ancestry-path")) {
2217                 revs->ancestry_path = 1;
2218                 revs->simplify_history = 0;
2219                 revs->limited = 1;
2220         } else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) {
2221                 init_reflog_walk(&revs->reflog_info);
2222         } else if (!strcmp(arg, "--default")) {
2223                 if (argc <= 1)
2224                         return error("bad --default argument");
2225                 revs->def = argv[1];
2226                 return 2;
2227         } else if (!strcmp(arg, "--merge")) {
2228                 revs->show_merge = 1;
2229         } else if (!strcmp(arg, "--topo-order")) {
2230                 revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
2231                 revs->topo_order = 1;
2232         } else if (!strcmp(arg, "--simplify-merges")) {
2233                 revs->simplify_merges = 1;
2234                 revs->topo_order = 1;
2235                 revs->rewrite_parents = 1;
2236                 revs->simplify_history = 0;
2237                 revs->limited = 1;
2238         } else if (!strcmp(arg, "--simplify-by-decoration")) {
2239                 revs->simplify_merges = 1;
2240                 revs->topo_order = 1;
2241                 revs->rewrite_parents = 1;
2242                 revs->simplify_history = 0;
2243                 revs->simplify_by_decoration = 1;
2244                 revs->limited = 1;
2245                 revs->prune = 1;
2246         } else if (!strcmp(arg, "--date-order")) {
2247                 revs->sort_order = REV_SORT_BY_COMMIT_DATE;
2248                 revs->topo_order = 1;
2249         } else if (!strcmp(arg, "--author-date-order")) {
2250                 revs->sort_order = REV_SORT_BY_AUTHOR_DATE;
2251                 revs->topo_order = 1;
2252         } else if (!strcmp(arg, "--early-output")) {
2253                 revs->early_output = 100;
2254                 revs->topo_order = 1;
2255         } else if (skip_prefix(arg, "--early-output=", &optarg)) {
2256                 if (strtoul_ui(optarg, 10, &revs->early_output) < 0)
2257                         die("'%s': not a non-negative integer", optarg);
2258                 revs->topo_order = 1;
2259         } else if (!strcmp(arg, "--parents")) {
2260                 revs->rewrite_parents = 1;
2261                 revs->print_parents = 1;
2262         } else if (!strcmp(arg, "--dense")) {
2263                 revs->dense = 1;
2264         } else if (!strcmp(arg, "--sparse")) {
2265                 revs->dense = 0;
2266         } else if (!strcmp(arg, "--in-commit-order")) {
2267                 revs->tree_blobs_in_commit_order = 1;
2268         } else if (!strcmp(arg, "--remove-empty")) {
2269                 revs->remove_empty_trees = 1;
2270         } else if (!strcmp(arg, "--merges")) {
2271                 revs->min_parents = 2;
2272         } else if (!strcmp(arg, "--no-merges")) {
2273                 revs->max_parents = 1;
2274         } else if (skip_prefix(arg, "--min-parents=", &optarg)) {
2275                 revs->min_parents = atoi(optarg);
2276         } else if (!strcmp(arg, "--no-min-parents")) {
2277                 revs->min_parents = 0;
2278         } else if (skip_prefix(arg, "--max-parents=", &optarg)) {
2279                 revs->max_parents = atoi(optarg);
2280         } else if (!strcmp(arg, "--no-max-parents")) {
2281                 revs->max_parents = -1;
2282         } else if (!strcmp(arg, "--boundary")) {
2283                 revs->boundary = 1;
2284         } else if (!strcmp(arg, "--left-right")) {
2285                 revs->left_right = 1;
2286         } else if (!strcmp(arg, "--left-only")) {
2287                 if (revs->right_only)
2288                         die("--left-only is incompatible with --right-only"
2289                             " or --cherry");
2290                 revs->left_only = 1;
2291         } else if (!strcmp(arg, "--right-only")) {
2292                 if (revs->left_only)
2293                         die("--right-only is incompatible with --left-only");
2294                 revs->right_only = 1;
2295         } else if (!strcmp(arg, "--cherry")) {
2296                 if (revs->left_only)
2297                         die("--cherry is incompatible with --left-only");
2298                 revs->cherry_mark = 1;
2299                 revs->right_only = 1;
2300                 revs->max_parents = 1;
2301                 revs->limited = 1;
2302         } else if (!strcmp(arg, "--count")) {
2303                 revs->count = 1;
2304         } else if (!strcmp(arg, "--cherry-mark")) {
2305                 if (revs->cherry_pick)
2306                         die("--cherry-mark is incompatible with --cherry-pick");
2307                 revs->cherry_mark = 1;
2308                 revs->limited = 1; /* needs limit_list() */
2309         } else if (!strcmp(arg, "--cherry-pick")) {
2310                 if (revs->cherry_mark)
2311                         die("--cherry-pick is incompatible with --cherry-mark");
2312                 revs->cherry_pick = 1;
2313                 revs->limited = 1;
2314         } else if (!strcmp(arg, "--objects")) {
2315                 revs->tag_objects = 1;
2316                 revs->tree_objects = 1;
2317                 revs->blob_objects = 1;
2318         } else if (!strcmp(arg, "--objects-edge")) {
2319                 revs->tag_objects = 1;
2320                 revs->tree_objects = 1;
2321                 revs->blob_objects = 1;
2322                 revs->edge_hint = 1;
2323         } else if (!strcmp(arg, "--objects-edge-aggressive")) {
2324                 revs->tag_objects = 1;
2325                 revs->tree_objects = 1;
2326                 revs->blob_objects = 1;
2327                 revs->edge_hint = 1;
2328                 revs->edge_hint_aggressive = 1;
2329         } else if (!strcmp(arg, "--verify-objects")) {
2330                 revs->tag_objects = 1;
2331                 revs->tree_objects = 1;
2332                 revs->blob_objects = 1;
2333                 revs->verify_objects = 1;
2334         } else if (!strcmp(arg, "--unpacked")) {
2335                 revs->unpacked = 1;
2336         } else if (starts_with(arg, "--unpacked=")) {
2337                 die("--unpacked=<packfile> no longer supported.");
2338         } else if (!strcmp(arg, "-r")) {
2339                 revs->diff = 1;
2340                 revs->diffopt.flags.recursive = 1;
2341         } else if (!strcmp(arg, "-t")) {
2342                 revs->diff = 1;
2343                 revs->diffopt.flags.recursive = 1;
2344                 revs->diffopt.flags.tree_in_recursive = 1;
2345         } else if (!strcmp(arg, "-m")) {
2346                 revs->ignore_merges = 0;
2347         } else if (!strcmp(arg, "-c")) {
2348                 revs->diff = 1;
2349                 revs->dense_combined_merges = 0;
2350                 revs->combine_merges = 1;
2351         } else if (!strcmp(arg, "--combined-all-paths")) {
2352                 revs->diff = 1;
2353                 revs->combined_all_paths = 1;
2354         } else if (!strcmp(arg, "--cc")) {
2355                 revs->diff = 1;
2356                 revs->dense_combined_merges = 1;
2357                 revs->combine_merges = 1;
2358         } else if (!strcmp(arg, "-v")) {
2359                 revs->verbose_header = 1;
2360         } else if (!strcmp(arg, "--pretty")) {
2361                 revs->verbose_header = 1;
2362                 revs->pretty_given = 1;
2363                 get_commit_format(NULL, revs);
2364         } else if (skip_prefix(arg, "--pretty=", &optarg) ||
2365                    skip_prefix(arg, "--format=", &optarg)) {
2366                 /*
2367                  * Detached form ("--pretty X" as opposed to "--pretty=X")
2368                  * not allowed, since the argument is optional.
2369                  */
2370                 revs->verbose_header = 1;
2371                 revs->pretty_given = 1;
2372                 get_commit_format(optarg, revs);
2373         } else if (!strcmp(arg, "--expand-tabs")) {
2374                 revs->expand_tabs_in_log = 8;
2375         } else if (!strcmp(arg, "--no-expand-tabs")) {
2376                 revs->expand_tabs_in_log = 0;
2377         } else if (skip_prefix(arg, "--expand-tabs=", &arg)) {
2378                 int val;
2379                 if (strtol_i(arg, 10, &val) < 0 || val < 0)
2380                         die("'%s': not a non-negative integer", arg);
2381                 revs->expand_tabs_in_log = val;
2382         } else if (!strcmp(arg, "--show-notes") || !strcmp(arg, "--notes")) {
2383                 enable_default_display_notes(&revs->notes_opt, &revs->show_notes);
2384                 revs->show_notes_given = 1;
2385         } else if (!strcmp(arg, "--show-signature")) {
2386                 revs->show_signature = 1;
2387         } else if (!strcmp(arg, "--no-show-signature")) {
2388                 revs->show_signature = 0;
2389         } else if (!strcmp(arg, "--show-linear-break")) {
2390                 revs->break_bar = "                    ..........";
2391                 revs->track_linear = 1;
2392                 revs->track_first_time = 1;
2393         } else if (skip_prefix(arg, "--show-linear-break=", &optarg)) {
2394                 revs->break_bar = xstrdup(optarg);
2395                 revs->track_linear = 1;
2396                 revs->track_first_time = 1;
2397         } else if (skip_prefix(arg, "--show-notes=", &optarg) ||
2398                    skip_prefix(arg, "--notes=", &optarg)) {
2399                 if (starts_with(arg, "--show-notes=") &&
2400                     revs->notes_opt.use_default_notes < 0)
2401                         revs->notes_opt.use_default_notes = 1;
2402                 enable_ref_display_notes(&revs->notes_opt, &revs->show_notes, optarg);
2403                 revs->show_notes_given = 1;
2404         } else if (!strcmp(arg, "--no-notes")) {
2405                 disable_display_notes(&revs->notes_opt, &revs->show_notes);
2406                 revs->show_notes_given = 1;
2407         } else if (!strcmp(arg, "--standard-notes")) {
2408                 revs->show_notes_given = 1;
2409                 revs->notes_opt.use_default_notes = 1;
2410         } else if (!strcmp(arg, "--no-standard-notes")) {
2411                 revs->notes_opt.use_default_notes = 0;
2412         } else if (!strcmp(arg, "--oneline")) {
2413                 revs->verbose_header = 1;
2414                 get_commit_format("oneline", revs);
2415                 revs->pretty_given = 1;
2416                 revs->abbrev_commit = 1;
2417         } else if (!strcmp(arg, "--graph")) {
2418                 revs->topo_order = 1;
2419                 revs->rewrite_parents = 1;
2420                 revs->graph = graph_init(revs);
2421         } else if (!strcmp(arg, "--encode-email-headers")) {
2422                 revs->encode_email_headers = 1;
2423         } else if (!strcmp(arg, "--no-encode-email-headers")) {
2424                 revs->encode_email_headers = 0;
2425         } else if (!strcmp(arg, "--root")) {
2426                 revs->show_root_diff = 1;
2427         } else if (!strcmp(arg, "--no-commit-id")) {
2428                 revs->no_commit_id = 1;
2429         } else if (!strcmp(arg, "--always")) {
2430                 revs->always_show_header = 1;
2431         } else if (!strcmp(arg, "--no-abbrev")) {
2432                 revs->abbrev = 0;
2433         } else if (!strcmp(arg, "--abbrev")) {
2434                 revs->abbrev = DEFAULT_ABBREV;
2435         } else if (skip_prefix(arg, "--abbrev=", &optarg)) {
2436                 revs->abbrev = strtoul(optarg, NULL, 10);
2437                 if (revs->abbrev < MINIMUM_ABBREV)
2438                         revs->abbrev = MINIMUM_ABBREV;
2439                 else if (revs->abbrev > hexsz)
2440                         revs->abbrev = hexsz;
2441         } else if (!strcmp(arg, "--abbrev-commit")) {
2442                 revs->abbrev_commit = 1;
2443                 revs->abbrev_commit_given = 1;
2444         } else if (!strcmp(arg, "--no-abbrev-commit")) {
2445                 revs->abbrev_commit = 0;
2446         } else if (!strcmp(arg, "--full-diff")) {
2447                 revs->diff = 1;
2448                 revs->full_diff = 1;
2449         } else if (!strcmp(arg, "--show-pulls")) {
2450                 revs->show_pulls = 1;
2451         } else if (!strcmp(arg, "--full-history")) {
2452                 revs->simplify_history = 0;
2453         } else if (!strcmp(arg, "--relative-date")) {
2454                 revs->date_mode.type = DATE_RELATIVE;
2455                 revs->date_mode_explicit = 1;
2456         } else if ((argcount = parse_long_opt("date", argv, &optarg))) {
2457                 parse_date_format(optarg, &revs->date_mode);
2458                 revs->date_mode_explicit = 1;
2459                 return argcount;
2460         } else if (!strcmp(arg, "--log-size")) {
2461                 revs->show_log_size = 1;
2462         }
2463         /*
2464          * Grepping the commit log
2465          */
2466         else if ((argcount = parse_long_opt("author", argv, &optarg))) {
2467                 add_header_grep(revs, GREP_HEADER_AUTHOR, optarg);
2468                 return argcount;
2469         } else if ((argcount = parse_long_opt("committer", argv, &optarg))) {
2470                 add_header_grep(revs, GREP_HEADER_COMMITTER, optarg);
2471                 return argcount;
2472         } else if ((argcount = parse_long_opt("grep-reflog", argv, &optarg))) {
2473                 add_header_grep(revs, GREP_HEADER_REFLOG, optarg);
2474                 return argcount;
2475         } else if ((argcount = parse_long_opt("grep", argv, &optarg))) {
2476                 add_message_grep(revs, optarg);
2477                 return argcount;
2478         } else if (!strcmp(arg, "--grep-debug")) {
2479                 revs->grep_filter.debug = 1;
2480         } else if (!strcmp(arg, "--basic-regexp")) {
2481                 revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_BRE;
2482         } else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) {
2483                 revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_ERE;
2484         } else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) {
2485                 revs->grep_filter.ignore_case = 1;
2486                 revs->diffopt.pickaxe_opts |= DIFF_PICKAXE_IGNORE_CASE;
2487         } else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) {
2488                 revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_FIXED;
2489         } else if (!strcmp(arg, "--perl-regexp") || !strcmp(arg, "-P")) {
2490                 revs->grep_filter.pattern_type_option = GREP_PATTERN_TYPE_PCRE;
2491         } else if (!strcmp(arg, "--all-match")) {
2492                 revs->grep_filter.all_match = 1;
2493         } else if (!strcmp(arg, "--invert-grep")) {
2494                 revs->invert_grep = 1;
2495         } else if ((argcount = parse_long_opt("encoding", argv, &optarg))) {
2496                 if (strcmp(optarg, "none"))
2497                         git_log_output_encoding = xstrdup(optarg);
2498                 else
2499                         git_log_output_encoding = "";
2500                 return argcount;
2501         } else if (!strcmp(arg, "--reverse")) {
2502                 revs->reverse ^= 1;
2503         } else if (!strcmp(arg, "--children")) {
2504                 revs->children.name = "children";
2505                 revs->limited = 1;
2506         } else if (!strcmp(arg, "--ignore-missing")) {
2507                 revs->ignore_missing = 1;
2508         } else if (opt && opt->allow_exclude_promisor_objects &&
2509                    !strcmp(arg, "--exclude-promisor-objects")) {
2510                 if (fetch_if_missing)
2511                         BUG("exclude_promisor_objects can only be used when fetch_if_missing is 0");
2512                 revs->exclude_promisor_objects = 1;
2513         } else {
2514                 int opts = diff_opt_parse(&revs->diffopt, argv, argc, revs->prefix);
2515                 if (!opts)
2516                         unkv[(*unkc)++] = arg;
2517                 return opts;
2518         }
2519         if (revs->graph && revs->track_linear)
2520                 die("--show-linear-break and --graph are incompatible");
2521
2522         return 1;
2523 }
2524
2525 void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx,
2526                         const struct option *options,
2527                         const char * const usagestr[])
2528 {
2529         int n = handle_revision_opt(revs, ctx->argc, ctx->argv,
2530                                     &ctx->cpidx, ctx->out, NULL);
2531         if (n <= 0) {
2532                 error("unknown option `%s'", ctx->argv[0]);
2533                 usage_with_options(usagestr, options);
2534         }
2535         ctx->argv += n;
2536         ctx->argc -= n;
2537 }
2538
2539 static int for_each_bisect_ref(struct ref_store *refs, each_ref_fn fn,
2540                                void *cb_data, const char *term)
2541 {
2542         struct strbuf bisect_refs = STRBUF_INIT;
2543         int status;
2544         strbuf_addf(&bisect_refs, "refs/bisect/%s", term);
2545         status = refs_for_each_fullref_in(refs, bisect_refs.buf, fn, cb_data, 0);
2546         strbuf_release(&bisect_refs);
2547         return status;
2548 }
2549
2550 static int for_each_bad_bisect_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
2551 {
2552         return for_each_bisect_ref(refs, fn, cb_data, term_bad);
2553 }
2554
2555 static int for_each_good_bisect_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
2556 {
2557         return for_each_bisect_ref(refs, fn, cb_data, term_good);
2558 }
2559
2560 static int handle_revision_pseudo_opt(const char *submodule,
2561                                 struct rev_info *revs,
2562                                 int argc, const char **argv, int *flags)
2563 {
2564         const char *arg = argv[0];
2565         const char *optarg;
2566         struct ref_store *refs;
2567         int argcount;
2568
2569         if (submodule) {
2570                 /*
2571                  * We need some something like get_submodule_worktrees()
2572                  * before we can go through all worktrees of a submodule,
2573                  * .e.g with adding all HEADs from --all, which is not
2574                  * supported right now, so stick to single worktree.
2575                  */
2576                 if (!revs->single_worktree)
2577                         BUG("--single-worktree cannot be used together with submodule");
2578                 refs = get_submodule_ref_store(submodule);
2579         } else
2580                 refs = get_main_ref_store(revs->repo);
2581
2582         /*
2583          * NOTE!
2584          *
2585          * Commands like "git shortlog" will not accept the options below
2586          * unless parse_revision_opt queues them (as opposed to erroring
2587          * out).
2588          *
2589          * When implementing your new pseudo-option, remember to
2590          * register it in the list at the top of handle_revision_opt.
2591          */
2592         if (!strcmp(arg, "--all")) {
2593                 handle_refs(refs, revs, *flags, refs_for_each_ref);
2594                 handle_refs(refs, revs, *flags, refs_head_ref);
2595                 if (!revs->single_worktree) {
2596                         struct all_refs_cb cb;
2597
2598                         init_all_refs_cb(&cb, revs, *flags);
2599                         other_head_refs(handle_one_ref, &cb);
2600                 }
2601                 clear_ref_exclusion(&revs->ref_excludes);
2602         } else if (!strcmp(arg, "--branches")) {
2603                 handle_refs(refs, revs, *flags, refs_for_each_branch_ref);
2604                 clear_ref_exclusion(&revs->ref_excludes);
2605         } else if (!strcmp(arg, "--bisect")) {
2606                 read_bisect_terms(&term_bad, &term_good);
2607                 handle_refs(refs, revs, *flags, for_each_bad_bisect_ref);
2608                 handle_refs(refs, revs, *flags ^ (UNINTERESTING | BOTTOM),
2609                             for_each_good_bisect_ref);
2610                 revs->bisect = 1;
2611         } else if (!strcmp(arg, "--tags")) {
2612                 handle_refs(refs, revs, *flags, refs_for_each_tag_ref);
2613                 clear_ref_exclusion(&revs->ref_excludes);
2614         } else if (!strcmp(arg, "--remotes")) {
2615                 handle_refs(refs, revs, *flags, refs_for_each_remote_ref);
2616                 clear_ref_exclusion(&revs->ref_excludes);
2617         } else if ((argcount = parse_long_opt("glob", argv, &optarg))) {
2618                 struct all_refs_cb cb;
2619                 init_all_refs_cb(&cb, revs, *flags);
2620                 for_each_glob_ref(handle_one_ref, optarg, &cb);
2621                 clear_ref_exclusion(&revs->ref_excludes);
2622                 return argcount;
2623         } else if ((argcount = parse_long_opt("exclude", argv, &optarg))) {
2624                 add_ref_exclusion(&revs->ref_excludes, optarg);
2625                 return argcount;
2626         } else if (skip_prefix(arg, "--branches=", &optarg)) {
2627                 struct all_refs_cb cb;
2628                 init_all_refs_cb(&cb, revs, *flags);
2629                 for_each_glob_ref_in(handle_one_ref, optarg, "refs/heads/", &cb);
2630                 clear_ref_exclusion(&revs->ref_excludes);
2631         } else if (skip_prefix(arg, "--tags=", &optarg)) {
2632                 struct all_refs_cb cb;
2633                 init_all_refs_cb(&cb, revs, *flags);
2634                 for_each_glob_ref_in(handle_one_ref, optarg, "refs/tags/", &cb);
2635                 clear_ref_exclusion(&revs->ref_excludes);
2636         } else if (skip_prefix(arg, "--remotes=", &optarg)) {
2637                 struct all_refs_cb cb;
2638                 init_all_refs_cb(&cb, revs, *flags);
2639                 for_each_glob_ref_in(handle_one_ref, optarg, "refs/remotes/", &cb);
2640                 clear_ref_exclusion(&revs->ref_excludes);
2641         } else if (!strcmp(arg, "--reflog")) {
2642                 add_reflogs_to_pending(revs, *flags);
2643         } else if (!strcmp(arg, "--indexed-objects")) {
2644                 add_index_objects_to_pending(revs, *flags);
2645         } else if (!strcmp(arg, "--alternate-refs")) {
2646                 add_alternate_refs_to_pending(revs, *flags);
2647         } else if (!strcmp(arg, "--not")) {
2648                 *flags ^= UNINTERESTING | BOTTOM;
2649         } else if (!strcmp(arg, "--no-walk")) {
2650                 revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
2651         } else if (skip_prefix(arg, "--no-walk=", &optarg)) {
2652                 /*
2653                  * Detached form ("--no-walk X" as opposed to "--no-walk=X")
2654                  * not allowed, since the argument is optional.
2655                  */
2656                 if (!strcmp(optarg, "sorted"))
2657                         revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
2658                 else if (!strcmp(optarg, "unsorted"))
2659                         revs->no_walk = REVISION_WALK_NO_WALK_UNSORTED;
2660                 else
2661                         return error("invalid argument to --no-walk");
2662         } else if (!strcmp(arg, "--do-walk")) {
2663                 revs->no_walk = 0;
2664         } else if (!strcmp(arg, "--single-worktree")) {
2665                 revs->single_worktree = 1;
2666         } else {
2667                 return 0;
2668         }
2669
2670         return 1;
2671 }
2672
2673 static void NORETURN diagnose_missing_default(const char *def)
2674 {
2675         int flags;
2676         const char *refname;
2677
2678         refname = resolve_ref_unsafe(def, 0, NULL, &flags);
2679         if (!refname || !(flags & REF_ISSYMREF) || (flags & REF_ISBROKEN))
2680                 die(_("your current branch appears to be broken"));
2681
2682         skip_prefix(refname, "refs/heads/", &refname);
2683         die(_("your current branch '%s' does not have any commits yet"),
2684             refname);
2685 }
2686
2687 /*
2688  * Parse revision information, filling in the "rev_info" structure,
2689  * and removing the used arguments from the argument list.
2690  *
2691  * Returns the number of arguments left that weren't recognized
2692  * (which are also moved to the head of the argument list)
2693  */
2694 int setup_revisions(int argc, const char **argv, struct rev_info *revs, struct setup_revision_opt *opt)
2695 {
2696         int i, flags, left, seen_dashdash, got_rev_arg = 0, revarg_opt;
2697         struct argv_array prune_data = ARGV_ARRAY_INIT;
2698         const char *submodule = NULL;
2699         int seen_end_of_options = 0;
2700
2701         if (opt)
2702                 submodule = opt->submodule;
2703
2704         /* First, search for "--" */
2705         if (opt && opt->assume_dashdash) {
2706                 seen_dashdash = 1;
2707         } else {
2708                 seen_dashdash = 0;
2709                 for (i = 1; i < argc; i++) {
2710                         const char *arg = argv[i];
2711                         if (strcmp(arg, "--"))
2712                                 continue;
2713                         argv[i] = NULL;
2714                         argc = i;
2715                         if (argv[i + 1])
2716                                 argv_array_pushv(&prune_data, argv + i + 1);
2717                         seen_dashdash = 1;
2718                         break;
2719                 }
2720         }
2721
2722         /* Second, deal with arguments and options */
2723         flags = 0;
2724         revarg_opt = opt ? opt->revarg_opt : 0;
2725         if (seen_dashdash)
2726                 revarg_opt |= REVARG_CANNOT_BE_FILENAME;
2727         for (left = i = 1; i < argc; i++) {
2728                 const char *arg = argv[i];
2729                 if (!seen_end_of_options && *arg == '-') {
2730                         int opts;
2731
2732                         opts = handle_revision_pseudo_opt(submodule,
2733                                                 revs, argc - i, argv + i,
2734                                                 &flags);
2735                         if (opts > 0) {
2736                                 i += opts - 1;
2737                                 continue;
2738                         }
2739
2740                         if (!strcmp(arg, "--stdin")) {
2741                                 if (revs->disable_stdin) {
2742                                         argv[left++] = arg;
2743                                         continue;
2744                                 }
2745                                 if (revs->read_from_stdin++)
2746                                         die("--stdin given twice?");
2747                                 read_revisions_from_stdin(revs, &prune_data);
2748                                 continue;
2749                         }
2750
2751                         if (!strcmp(arg, "--end-of-options")) {
2752                                 seen_end_of_options = 1;
2753                                 continue;
2754                         }
2755
2756                         opts = handle_revision_opt(revs, argc - i, argv + i,
2757                                                    &left, argv, opt);
2758                         if (opts > 0) {
2759                                 i += opts - 1;
2760                                 continue;
2761                         }
2762                         if (opts < 0)
2763                                 exit(128);
2764                         continue;
2765                 }
2766
2767
2768                 if (handle_revision_arg(arg, revs, flags, revarg_opt)) {
2769                         int j;
2770                         if (seen_dashdash || *arg == '^')
2771                                 die("bad revision '%s'", arg);
2772
2773                         /* If we didn't have a "--":
2774                          * (1) all filenames must exist;
2775                          * (2) all rev-args must not be interpretable
2776                          *     as a valid filename.
2777                          * but the latter we have checked in the main loop.
2778                          */
2779                         for (j = i; j < argc; j++)
2780                                 verify_filename(revs->prefix, argv[j], j == i);
2781
2782                         argv_array_pushv(&prune_data, argv + i);
2783                         break;
2784                 }
2785                 else
2786                         got_rev_arg = 1;
2787         }
2788
2789         if (prune_data.argc) {
2790                 /*
2791                  * If we need to introduce the magic "a lone ':' means no
2792                  * pathspec whatsoever", here is the place to do so.
2793                  *
2794                  * if (prune_data.nr == 1 && !strcmp(prune_data[0], ":")) {
2795                  *      prune_data.nr = 0;
2796                  *      prune_data.alloc = 0;
2797                  *      free(prune_data.path);
2798                  *      prune_data.path = NULL;
2799                  * } else {
2800                  *      terminate prune_data.alloc with NULL and
2801                  *      call init_pathspec() to set revs->prune_data here.
2802                  * }
2803                  */
2804                 parse_pathspec(&revs->prune_data, 0, 0,
2805                                revs->prefix, prune_data.argv);
2806         }
2807         argv_array_clear(&prune_data);
2808
2809         if (revs->def == NULL)
2810                 revs->def = opt ? opt->def : NULL;
2811         if (opt && opt->tweak)
2812                 opt->tweak(revs, opt);
2813         if (revs->show_merge)
2814                 prepare_show_merge(revs);
2815         if (revs->def && !revs->pending.nr && !revs->rev_input_given && !got_rev_arg) {
2816                 struct object_id oid;
2817                 struct object *object;
2818                 struct object_context oc;
2819                 if (get_oid_with_context(revs->repo, revs->def, 0, &oid, &oc))
2820                         diagnose_missing_default(revs->def);
2821                 object = get_reference(revs, revs->def, &oid, 0);
2822                 add_pending_object_with_mode(revs, object, revs->def, oc.mode);
2823         }
2824
2825         /* Did the user ask for any diff output? Run the diff! */
2826         if (revs->diffopt.output_format & ~DIFF_FORMAT_NO_OUTPUT)
2827                 revs->diff = 1;
2828
2829         /* Pickaxe, diff-filter and rename following need diffs */
2830         if ((revs->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
2831             revs->diffopt.filter ||
2832             revs->diffopt.flags.follow_renames)
2833                 revs->diff = 1;
2834
2835         if (revs->diffopt.objfind)
2836                 revs->simplify_history = 0;
2837
2838         if (revs->line_level_traverse) {
2839                 if (want_ancestry(revs))
2840                         revs->limited = 1;
2841                 revs->topo_order = 1;
2842         }
2843
2844         if (revs->topo_order && !generation_numbers_enabled(the_repository))
2845                 revs->limited = 1;
2846
2847         if (revs->prune_data.nr) {
2848                 copy_pathspec(&revs->pruning.pathspec, &revs->prune_data);
2849                 /* Can't prune commits with rename following: the paths change.. */
2850                 if (!revs->diffopt.flags.follow_renames)
2851                         revs->prune = 1;
2852                 if (!revs->full_diff)
2853                         copy_pathspec(&revs->diffopt.pathspec,
2854                                       &revs->prune_data);
2855         }
2856         if (revs->combine_merges)
2857                 revs->ignore_merges = 0;
2858         if (revs->combined_all_paths && !revs->combine_merges)
2859                 die("--combined-all-paths makes no sense without -c or --cc");
2860
2861         revs->diffopt.abbrev = revs->abbrev;
2862
2863         diff_setup_done(&revs->diffopt);
2864
2865         grep_commit_pattern_type(GREP_PATTERN_TYPE_UNSPECIFIED,
2866                                  &revs->grep_filter);
2867         if (!is_encoding_utf8(get_log_output_encoding()))
2868                 revs->grep_filter.ignore_locale = 1;
2869         compile_grep_patterns(&revs->grep_filter);
2870
2871         if (revs->reverse && revs->reflog_info)
2872                 die("cannot combine --reverse with --walk-reflogs");
2873         if (revs->reflog_info && revs->limited)
2874                 die("cannot combine --walk-reflogs with history-limiting options");
2875         if (revs->rewrite_parents && revs->children.name)
2876                 die("cannot combine --parents and --children");
2877
2878         /*
2879          * Limitations on the graph functionality
2880          */
2881         if (revs->reverse && revs->graph)
2882                 die("cannot combine --reverse with --graph");
2883
2884         if (revs->reflog_info && revs->graph)
2885                 die("cannot combine --walk-reflogs with --graph");
2886         if (revs->no_walk && revs->graph)
2887                 die("cannot combine --no-walk with --graph");
2888         if (!revs->reflog_info && revs->grep_filter.use_reflog_filter)
2889                 die("cannot use --grep-reflog without --walk-reflogs");
2890
2891         if (revs->first_parent_only && revs->bisect)
2892                 die(_("--first-parent is incompatible with --bisect"));
2893
2894         if (revs->line_level_traverse &&
2895             (revs->diffopt.output_format & ~(DIFF_FORMAT_PATCH | DIFF_FORMAT_NO_OUTPUT)))
2896                 die(_("-L does not yet support diff formats besides -p and -s"));
2897
2898         if (revs->expand_tabs_in_log < 0)
2899                 revs->expand_tabs_in_log = revs->expand_tabs_in_log_default;
2900
2901         return left;
2902 }
2903
2904 static void add_child(struct rev_info *revs, struct commit *parent, struct commit *child)
2905 {
2906         struct commit_list *l = xcalloc(1, sizeof(*l));
2907
2908         l->item = child;
2909         l->next = add_decoration(&revs->children, &parent->object, l);
2910 }
2911
2912 static int remove_duplicate_parents(struct rev_info *revs, struct commit *commit)
2913 {
2914         struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
2915         struct commit_list **pp, *p;
2916         int surviving_parents;
2917
2918         /* Examine existing parents while marking ones we have seen... */
2919         pp = &commit->parents;
2920         surviving_parents = 0;
2921         while ((p = *pp) != NULL) {
2922                 struct commit *parent = p->item;
2923                 if (parent->object.flags & TMP_MARK) {
2924                         *pp = p->next;
2925                         if (ts)
2926                                 compact_treesame(revs, commit, surviving_parents);
2927                         continue;
2928                 }
2929                 parent->object.flags |= TMP_MARK;
2930                 surviving_parents++;
2931                 pp = &p->next;
2932         }
2933         /* clear the temporary mark */
2934         for (p = commit->parents; p; p = p->next) {
2935                 p->item->object.flags &= ~TMP_MARK;
2936         }
2937         /* no update_treesame() - removing duplicates can't affect TREESAME */
2938         return surviving_parents;
2939 }
2940
2941 struct merge_simplify_state {
2942         struct commit *simplified;
2943 };
2944
2945 static struct merge_simplify_state *locate_simplify_state(struct rev_info *revs, struct commit *commit)
2946 {
2947         struct merge_simplify_state *st;
2948
2949         st = lookup_decoration(&revs->merge_simplification, &commit->object);
2950         if (!st) {
2951                 st = xcalloc(1, sizeof(*st));
2952                 add_decoration(&revs->merge_simplification, &commit->object, st);
2953         }
2954         return st;
2955 }
2956
2957 static int mark_redundant_parents(struct commit *commit)
2958 {
2959         struct commit_list *h = reduce_heads(commit->parents);
2960         int i = 0, marked = 0;
2961         struct commit_list *po, *pn;
2962
2963         /* Want these for sanity-checking only */
2964         int orig_cnt = commit_list_count(commit->parents);
2965         int cnt = commit_list_count(h);
2966
2967         /*
2968          * Not ready to remove items yet, just mark them for now, based
2969          * on the output of reduce_heads(). reduce_heads outputs the reduced
2970          * set in its original order, so this isn't too hard.
2971          */
2972         po = commit->parents;
2973         pn = h;
2974         while (po) {
2975                 if (pn && po->item == pn->item) {
2976                         pn = pn->next;
2977                         i++;
2978                 } else {
2979                         po->item->object.flags |= TMP_MARK;
2980                         marked++;
2981                 }
2982                 po=po->next;
2983         }
2984
2985         if (i != cnt || cnt+marked != orig_cnt)
2986                 die("mark_redundant_parents %d %d %d %d", orig_cnt, cnt, i, marked);
2987
2988         free_commit_list(h);
2989
2990         return marked;
2991 }
2992
2993 static int mark_treesame_root_parents(struct commit *commit)
2994 {
2995         struct commit_list *p;
2996         int marked = 0;
2997
2998         for (p = commit->parents; p; p = p->next) {
2999                 struct commit *parent = p->item;
3000                 if (!parent->parents && (parent->object.flags & TREESAME)) {
3001                         parent->object.flags |= TMP_MARK;
3002                         marked++;
3003                 }
3004         }
3005
3006         return marked;
3007 }
3008
3009 /*
3010  * Awkward naming - this means one parent we are TREESAME to.
3011  * cf mark_treesame_root_parents: root parents that are TREESAME (to an
3012  * empty tree). Better name suggestions?
3013  */
3014 static int leave_one_treesame_to_parent(struct rev_info *revs, struct commit *commit)
3015 {
3016         struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
3017         struct commit *unmarked = NULL, *marked = NULL;
3018         struct commit_list *p;
3019         unsigned n;
3020
3021         for (p = commit->parents, n = 0; p; p = p->next, n++) {
3022                 if (ts->treesame[n]) {
3023                         if (p->item->object.flags & TMP_MARK) {
3024                                 if (!marked)
3025                                         marked = p->item;
3026                         } else {
3027                                 if (!unmarked) {
3028                                         unmarked = p->item;
3029                                         break;
3030                                 }
3031                         }
3032                 }
3033         }
3034
3035         /*
3036          * If we are TREESAME to a marked-for-deletion parent, but not to any
3037          * unmarked parents, unmark the first TREESAME parent. This is the
3038          * parent that the default simplify_history==1 scan would have followed,
3039          * and it doesn't make sense to omit that path when asking for a
3040          * simplified full history. Retaining it improves the chances of
3041          * understanding odd missed merges that took an old version of a file.
3042          *
3043          * Example:
3044          *
3045          *   I--------*X       A modified the file, but mainline merge X used
3046          *    \       /        "-s ours", so took the version from I. X is
3047          *     `-*A--'         TREESAME to I and !TREESAME to A.
3048          *
3049          * Default log from X would produce "I". Without this check,
3050          * --full-history --simplify-merges would produce "I-A-X", showing
3051          * the merge commit X and that it changed A, but not making clear that
3052          * it had just taken the I version. With this check, the topology above
3053          * is retained.
3054          *
3055          * Note that it is possible that the simplification chooses a different
3056          * TREESAME parent from the default, in which case this test doesn't
3057          * activate, and we _do_ drop the default parent. Example:
3058          *
3059          *   I------X         A modified the file, but it was reverted in B,
3060          *    \    /          meaning mainline merge X is TREESAME to both
3061          *    *A-*B           parents.
3062          *
3063          * Default log would produce "I" by following the first parent;
3064          * --full-history --simplify-merges will produce "I-A-B". But this is a
3065          * reasonable result - it presents a logical full history leading from
3066          * I to X, and X is not an important merge.
3067          */
3068         if (!unmarked && marked) {
3069                 marked->object.flags &= ~TMP_MARK;
3070                 return 1;
3071         }
3072
3073         return 0;
3074 }
3075
3076 static int remove_marked_parents(struct rev_info *revs, struct commit *commit)
3077 {
3078         struct commit_list **pp, *p;
3079         int nth_parent, removed = 0;
3080
3081         pp = &commit->parents;
3082         nth_parent = 0;
3083         while ((p = *pp) != NULL) {
3084                 struct commit *parent = p->item;
3085                 if (parent->object.flags & TMP_MARK) {
3086                         parent->object.flags &= ~TMP_MARK;
3087                         *pp = p->next;
3088                         free(p);
3089                         removed++;
3090                         compact_treesame(revs, commit, nth_parent);
3091                         continue;
3092                 }
3093                 pp = &p->next;
3094                 nth_parent++;
3095         }
3096
3097         /* Removing parents can only increase TREESAMEness */
3098         if (removed && !(commit->object.flags & TREESAME))
3099                 update_treesame(revs, commit);
3100
3101         return nth_parent;
3102 }
3103
3104 static struct commit_list **simplify_one(struct rev_info *revs, struct commit *commit, struct commit_list **tail)
3105 {
3106         struct commit_list *p;
3107         struct commit *parent;
3108         struct merge_simplify_state *st, *pst;
3109         int cnt;
3110
3111         st = locate_simplify_state(revs, commit);
3112
3113         /*
3114          * Have we handled this one?
3115          */
3116         if (st->simplified)
3117                 return tail;
3118
3119         /*
3120          * An UNINTERESTING commit simplifies to itself, so does a
3121          * root commit.  We do not rewrite parents of such commit
3122          * anyway.
3123          */
3124         if ((commit->object.flags & UNINTERESTING) || !commit->parents) {
3125                 st->simplified = commit;
3126                 return tail;
3127         }
3128
3129         /*
3130          * Do we know what commit all of our parents that matter
3131          * should be rewritten to?  Otherwise we are not ready to
3132          * rewrite this one yet.
3133          */
3134         for (cnt = 0, p = commit->parents; p; p = p->next) {
3135                 pst = locate_simplify_state(revs, p->item);
3136                 if (!pst->simplified) {
3137                         tail = &commit_list_insert(p->item, tail)->next;
3138                         cnt++;
3139                 }
3140                 if (revs->first_parent_only)
3141                         break;
3142         }
3143         if (cnt) {
3144                 tail = &commit_list_insert(commit, tail)->next;
3145                 return tail;
3146         }
3147
3148         /*
3149          * Rewrite our list of parents. Note that this cannot
3150          * affect our TREESAME flags in any way - a commit is
3151          * always TREESAME to its simplification.
3152          */
3153         for (p = commit->parents; p; p = p->next) {
3154                 pst = locate_simplify_state(revs, p->item);
3155                 p->item = pst->simplified;
3156                 if (revs->first_parent_only)
3157                         break;
3158         }
3159
3160         if (revs->first_parent_only)
3161                 cnt = 1;
3162         else
3163                 cnt = remove_duplicate_parents(revs, commit);
3164
3165         /*
3166          * It is possible that we are a merge and one side branch
3167          * does not have any commit that touches the given paths;
3168          * in such a case, the immediate parent from that branch
3169          * will be rewritten to be the merge base.
3170          *
3171          *      o----X          X: the commit we are looking at;
3172          *     /    /           o: a commit that touches the paths;
3173          * ---o----'
3174          *
3175          * Further, a merge of an independent branch that doesn't
3176          * touch the path will reduce to a treesame root parent:
3177          *
3178          *  ----o----X          X: the commit we are looking at;
3179          *          /           o: a commit that touches the paths;
3180          *         r            r: a root commit not touching the paths
3181          *
3182          * Detect and simplify both cases.
3183          */
3184         if (1 < cnt) {
3185                 int marked = mark_redundant_parents(commit);
3186                 marked += mark_treesame_root_parents(commit);
3187                 if (marked)
3188                         marked -= leave_one_treesame_to_parent(revs, commit);
3189                 if (marked)
3190                         cnt = remove_marked_parents(revs, commit);
3191         }
3192
3193         /*
3194          * A commit simplifies to itself if it is a root, if it is
3195          * UNINTERESTING, if it touches the given paths, or if it is a
3196          * merge and its parents don't simplify to one relevant commit
3197          * (the first two cases are already handled at the beginning of
3198          * this function).
3199          *
3200          * Otherwise, it simplifies to what its sole relevant parent
3201          * simplifies to.
3202          */
3203         if (!cnt ||
3204             (commit->object.flags & UNINTERESTING) ||
3205             !(commit->object.flags & TREESAME) ||
3206             (parent = one_relevant_parent(revs, commit->parents)) == NULL ||
3207             (revs->show_pulls && (commit->object.flags & PULL_MERGE)))
3208                 st->simplified = commit;
3209         else {
3210                 pst = locate_simplify_state(revs, parent);
3211                 st->simplified = pst->simplified;
3212         }
3213         return tail;
3214 }
3215
3216 static void simplify_merges(struct rev_info *revs)
3217 {
3218         struct commit_list *list, *next;
3219         struct commit_list *yet_to_do, **tail;
3220         struct commit *commit;
3221
3222         if (!revs->prune)
3223                 return;
3224
3225         /* feed the list reversed */
3226         yet_to_do = NULL;
3227         for (list = revs->commits; list; list = next) {
3228                 commit = list->item;
3229                 next = list->next;
3230                 /*
3231                  * Do not free(list) here yet; the original list
3232                  * is used later in this function.
3233                  */
3234                 commit_list_insert(commit, &yet_to_do);
3235         }
3236         while (yet_to_do) {
3237                 list = yet_to_do;
3238                 yet_to_do = NULL;
3239                 tail = &yet_to_do;
3240                 while (list) {
3241                         commit = pop_commit(&list);
3242                         tail = simplify_one(revs, commit, tail);
3243                 }
3244         }
3245
3246         /* clean up the result, removing the simplified ones */
3247         list = revs->commits;
3248         revs->commits = NULL;
3249         tail = &revs->commits;
3250         while (list) {
3251                 struct merge_simplify_state *st;
3252
3253                 commit = pop_commit(&list);
3254                 st = locate_simplify_state(revs, commit);
3255                 if (st->simplified == commit)
3256                         tail = &commit_list_insert(commit, tail)->next;
3257         }
3258 }
3259
3260 static void set_children(struct rev_info *revs)
3261 {
3262         struct commit_list *l;
3263         for (l = revs->commits; l; l = l->next) {
3264                 struct commit *commit = l->item;
3265                 struct commit_list *p;
3266
3267                 for (p = commit->parents; p; p = p->next)
3268                         add_child(revs, p->item, commit);
3269         }
3270 }
3271
3272 void reset_revision_walk(void)
3273 {
3274         clear_object_flags(SEEN | ADDED | SHOWN | TOPO_WALK_EXPLORED | TOPO_WALK_INDEGREE);
3275 }
3276
3277 static int mark_uninteresting(const struct object_id *oid,
3278                               struct packed_git *pack,
3279                               uint32_t pos,
3280                               void *cb)
3281 {
3282         struct rev_info *revs = cb;
3283         struct object *o = parse_object(revs->repo, oid);
3284         o->flags |= UNINTERESTING | SEEN;
3285         return 0;
3286 }
3287
3288 define_commit_slab(indegree_slab, int);
3289 define_commit_slab(author_date_slab, timestamp_t);
3290
3291 struct topo_walk_info {
3292         uint32_t min_generation;
3293         struct prio_queue explore_queue;
3294         struct prio_queue indegree_queue;
3295         struct prio_queue topo_queue;
3296         struct indegree_slab indegree;
3297         struct author_date_slab author_date;
3298 };
3299
3300 static inline void test_flag_and_insert(struct prio_queue *q, struct commit *c, int flag)
3301 {
3302         if (c->object.flags & flag)
3303                 return;
3304
3305         c->object.flags |= flag;
3306         prio_queue_put(q, c);
3307 }
3308
3309 static void explore_walk_step(struct rev_info *revs)
3310 {
3311         struct topo_walk_info *info = revs->topo_walk_info;
3312         struct commit_list *p;
3313         struct commit *c = prio_queue_get(&info->explore_queue);
3314
3315         if (!c)
3316                 return;
3317
3318         if (parse_commit_gently(c, 1) < 0)
3319                 return;
3320
3321         if (revs->sort_order == REV_SORT_BY_AUTHOR_DATE)
3322                 record_author_date(&info->author_date, c);
3323
3324         if (revs->max_age != -1 && (c->date < revs->max_age))
3325                 c->object.flags |= UNINTERESTING;
3326
3327         if (process_parents(revs, c, NULL, NULL) < 0)
3328                 return;
3329
3330         if (c->object.flags & UNINTERESTING)
3331                 mark_parents_uninteresting(c);
3332
3333         for (p = c->parents; p; p = p->next)
3334                 test_flag_and_insert(&info->explore_queue, p->item, TOPO_WALK_EXPLORED);
3335 }
3336
3337 static void explore_to_depth(struct rev_info *revs,
3338                              uint32_t gen_cutoff)
3339 {
3340         struct topo_walk_info *info = revs->topo_walk_info;
3341         struct commit *c;
3342         while ((c = prio_queue_peek(&info->explore_queue)) &&
3343                commit_graph_generation(c) >= gen_cutoff)
3344                 explore_walk_step(revs);
3345 }
3346
3347 static void indegree_walk_step(struct rev_info *revs)
3348 {
3349         struct commit_list *p;
3350         struct topo_walk_info *info = revs->topo_walk_info;
3351         struct commit *c = prio_queue_get(&info->indegree_queue);
3352
3353         if (!c)
3354                 return;
3355
3356         if (parse_commit_gently(c, 1) < 0)
3357                 return;
3358
3359         explore_to_depth(revs, commit_graph_generation(c));
3360
3361         for (p = c->parents; p; p = p->next) {
3362                 struct commit *parent = p->item;
3363                 int *pi = indegree_slab_at(&info->indegree, parent);
3364
3365                 if (*pi)
3366                         (*pi)++;
3367                 else
3368                         *pi = 2;
3369
3370                 test_flag_and_insert(&info->indegree_queue, parent, TOPO_WALK_INDEGREE);
3371
3372                 if (revs->first_parent_only)
3373                         return;
3374         }
3375 }
3376
3377 static void compute_indegrees_to_depth(struct rev_info *revs,
3378                                        uint32_t gen_cutoff)
3379 {
3380         struct topo_walk_info *info = revs->topo_walk_info;
3381         struct commit *c;
3382         while ((c = prio_queue_peek(&info->indegree_queue)) &&
3383                commit_graph_generation(c) >= gen_cutoff)
3384                 indegree_walk_step(revs);
3385 }
3386
3387 static void reset_topo_walk(struct rev_info *revs)
3388 {
3389         struct topo_walk_info *info = revs->topo_walk_info;
3390
3391         clear_prio_queue(&info->explore_queue);
3392         clear_prio_queue(&info->indegree_queue);
3393         clear_prio_queue(&info->topo_queue);
3394         clear_indegree_slab(&info->indegree);
3395         clear_author_date_slab(&info->author_date);
3396
3397         FREE_AND_NULL(revs->topo_walk_info);
3398 }
3399
3400 static void init_topo_walk(struct rev_info *revs)
3401 {
3402         struct topo_walk_info *info;
3403         struct commit_list *list;
3404         if (revs->topo_walk_info)
3405                 reset_topo_walk(revs);
3406
3407         revs->topo_walk_info = xmalloc(sizeof(struct topo_walk_info));
3408         info = revs->topo_walk_info;
3409         memset(info, 0, sizeof(struct topo_walk_info));
3410
3411         init_indegree_slab(&info->indegree);
3412         memset(&info->explore_queue, 0, sizeof(info->explore_queue));
3413         memset(&info->indegree_queue, 0, sizeof(info->indegree_queue));
3414         memset(&info->topo_queue, 0, sizeof(info->topo_queue));
3415
3416         switch (revs->sort_order) {
3417         default: /* REV_SORT_IN_GRAPH_ORDER */
3418                 info->topo_queue.compare = NULL;
3419                 break;
3420         case REV_SORT_BY_COMMIT_DATE:
3421                 info->topo_queue.compare = compare_commits_by_commit_date;
3422                 break;
3423         case REV_SORT_BY_AUTHOR_DATE:
3424                 init_author_date_slab(&info->author_date);
3425                 info->topo_queue.compare = compare_commits_by_author_date;
3426                 info->topo_queue.cb_data = &info->author_date;
3427                 break;
3428         }
3429
3430         info->explore_queue.compare = compare_commits_by_gen_then_commit_date;
3431         info->indegree_queue.compare = compare_commits_by_gen_then_commit_date;
3432
3433         info->min_generation = GENERATION_NUMBER_INFINITY;
3434         for (list = revs->commits; list; list = list->next) {
3435                 struct commit *c = list->item;
3436                 uint32_t generation;
3437
3438                 if (parse_commit_gently(c, 1))
3439                         continue;
3440
3441                 test_flag_and_insert(&info->explore_queue, c, TOPO_WALK_EXPLORED);
3442                 test_flag_and_insert(&info->indegree_queue, c, TOPO_WALK_INDEGREE);
3443
3444                 generation = commit_graph_generation(c);
3445                 if (generation < info->min_generation)
3446                         info->min_generation = generation;
3447
3448                 *(indegree_slab_at(&info->indegree, c)) = 1;
3449
3450                 if (revs->sort_order == REV_SORT_BY_AUTHOR_DATE)
3451                         record_author_date(&info->author_date, c);
3452         }
3453         compute_indegrees_to_depth(revs, info->min_generation);
3454
3455         for (list = revs->commits; list; list = list->next) {
3456                 struct commit *c = list->item;
3457
3458                 if (*(indegree_slab_at(&info->indegree, c)) == 1)
3459                         prio_queue_put(&info->topo_queue, c);
3460         }
3461
3462         /*
3463          * This is unfortunate; the initial tips need to be shown
3464          * in the order given from the revision traversal machinery.
3465          */
3466         if (revs->sort_order == REV_SORT_IN_GRAPH_ORDER)
3467                 prio_queue_reverse(&info->topo_queue);
3468 }
3469
3470 static struct commit *next_topo_commit(struct rev_info *revs)
3471 {
3472         struct commit *c;
3473         struct topo_walk_info *info = revs->topo_walk_info;
3474
3475         /* pop next off of topo_queue */
3476         c = prio_queue_get(&info->topo_queue);
3477
3478         if (c)
3479                 *(indegree_slab_at(&info->indegree, c)) = 0;
3480
3481         return c;
3482 }
3483
3484 static void expand_topo_walk(struct rev_info *revs, struct commit *commit)
3485 {
3486         struct commit_list *p;
3487         struct topo_walk_info *info = revs->topo_walk_info;
3488         if (process_parents(revs, commit, NULL, NULL) < 0) {
3489                 if (!revs->ignore_missing_links)
3490                         die("Failed to traverse parents of commit %s",
3491                             oid_to_hex(&commit->object.oid));
3492         }
3493
3494         for (p = commit->parents; p; p = p->next) {
3495                 struct commit *parent = p->item;
3496                 int *pi;
3497                 uint32_t generation;
3498
3499                 if (parent->object.flags & UNINTERESTING)
3500                         continue;
3501
3502                 if (parse_commit_gently(parent, 1) < 0)
3503                         continue;
3504
3505                 generation = commit_graph_generation(parent);
3506                 if (generation < info->min_generation) {
3507                         info->min_generation = generation;
3508                         compute_indegrees_to_depth(revs, info->min_generation);
3509                 }
3510
3511                 pi = indegree_slab_at(&info->indegree, parent);
3512
3513                 (*pi)--;
3514                 if (*pi == 1)
3515                         prio_queue_put(&info->topo_queue, parent);
3516
3517                 if (revs->first_parent_only)
3518                         return;
3519         }
3520 }
3521
3522 int prepare_revision_walk(struct rev_info *revs)
3523 {
3524         int i;
3525         struct object_array old_pending;
3526         struct commit_list **next = &revs->commits;
3527
3528         memcpy(&old_pending, &revs->pending, sizeof(old_pending));
3529         revs->pending.nr = 0;
3530         revs->pending.alloc = 0;
3531         revs->pending.objects = NULL;
3532         for (i = 0; i < old_pending.nr; i++) {
3533                 struct object_array_entry *e = old_pending.objects + i;
3534                 struct commit *commit = handle_commit(revs, e);
3535                 if (commit) {
3536                         if (!(commit->object.flags & SEEN)) {
3537                                 commit->object.flags |= SEEN;
3538                                 next = commit_list_append(commit, next);
3539                         }
3540                 }
3541         }
3542         object_array_clear(&old_pending);
3543
3544         /* Signal whether we need per-parent treesame decoration */
3545         if (revs->simplify_merges ||
3546             (revs->limited && limiting_can_increase_treesame(revs)))
3547                 revs->treesame.name = "treesame";
3548
3549         if (revs->exclude_promisor_objects) {
3550                 for_each_packed_object(mark_uninteresting, revs,
3551                                        FOR_EACH_OBJECT_PROMISOR_ONLY);
3552         }
3553
3554         if (!revs->reflog_info)
3555                 prepare_to_use_bloom_filter(revs);
3556         if (revs->no_walk != REVISION_WALK_NO_WALK_UNSORTED)
3557                 commit_list_sort_by_date(&revs->commits);
3558         if (revs->no_walk)
3559                 return 0;
3560         if (revs->limited) {
3561                 if (limit_list(revs) < 0)
3562                         return -1;
3563                 if (revs->topo_order)
3564                         sort_in_topological_order(&revs->commits, revs->sort_order);
3565         } else if (revs->topo_order)
3566                 init_topo_walk(revs);
3567         if (revs->line_level_traverse && want_ancestry(revs))
3568                 /*
3569                  * At the moment we can only do line-level log with parent
3570                  * rewriting by performing this expensive pre-filtering step.
3571                  * If parent rewriting is not requested, then we rather
3572                  * perform the line-level log filtering during the regular
3573                  * history traversal.
3574                  */
3575                 line_log_filter(revs);
3576         if (revs->simplify_merges)
3577                 simplify_merges(revs);
3578         if (revs->children.name)
3579                 set_children(revs);
3580
3581         return 0;
3582 }
3583
3584 static enum rewrite_result rewrite_one_1(struct rev_info *revs,
3585                                          struct commit **pp,
3586                                          struct prio_queue *queue)
3587 {
3588         for (;;) {
3589                 struct commit *p = *pp;
3590                 if (!revs->limited)
3591                         if (process_parents(revs, p, NULL, queue) < 0)
3592                                 return rewrite_one_error;
3593                 if (p->object.flags & UNINTERESTING)
3594                         return rewrite_one_ok;
3595                 if (!(p->object.flags & TREESAME))
3596                         return rewrite_one_ok;
3597                 if (!p->parents)
3598                         return rewrite_one_noparents;
3599                 if ((p = one_relevant_parent(revs, p->parents)) == NULL)
3600                         return rewrite_one_ok;
3601                 *pp = p;
3602         }
3603 }
3604
3605 static void merge_queue_into_list(struct prio_queue *q, struct commit_list **list)
3606 {
3607         while (q->nr) {
3608                 struct commit *item = prio_queue_peek(q);
3609                 struct commit_list *p = *list;
3610
3611                 if (p && p->item->date >= item->date)
3612                         list = &p->next;
3613                 else {
3614                         p = commit_list_insert(item, list);
3615                         list = &p->next; /* skip newly added item */
3616                         prio_queue_get(q); /* pop item */
3617                 }
3618         }
3619 }
3620
3621 static enum rewrite_result rewrite_one(struct rev_info *revs, struct commit **pp)
3622 {
3623         struct prio_queue queue = { compare_commits_by_commit_date };
3624         enum rewrite_result ret = rewrite_one_1(revs, pp, &queue);
3625         merge_queue_into_list(&queue, &revs->commits);
3626         clear_prio_queue(&queue);
3627         return ret;
3628 }
3629
3630 int rewrite_parents(struct rev_info *revs, struct commit *commit,
3631         rewrite_parent_fn_t rewrite_parent)
3632 {
3633         struct commit_list **pp = &commit->parents;
3634         while (*pp) {
3635                 struct commit_list *parent = *pp;
3636                 switch (rewrite_parent(revs, &parent->item)) {
3637                 case rewrite_one_ok:
3638                         break;
3639                 case rewrite_one_noparents:
3640                         *pp = parent->next;
3641                         continue;
3642                 case rewrite_one_error:
3643                         return -1;
3644                 }
3645                 pp = &parent->next;
3646         }
3647         remove_duplicate_parents(revs, commit);
3648         return 0;
3649 }
3650
3651 static int commit_rewrite_person(struct strbuf *buf, const char *what, struct string_list *mailmap)
3652 {
3653         char *person, *endp;
3654         size_t len, namelen, maillen;
3655         const char *name;
3656         const char *mail;
3657         struct ident_split ident;
3658
3659         person = strstr(buf->buf, what);
3660         if (!person)
3661                 return 0;
3662
3663         person += strlen(what);
3664         endp = strchr(person, '\n');
3665         if (!endp)
3666                 return 0;
3667
3668         len = endp - person;
3669
3670         if (split_ident_line(&ident, person, len))
3671                 return 0;
3672
3673         mail = ident.mail_begin;
3674         maillen = ident.mail_end - ident.mail_begin;
3675         name = ident.name_begin;
3676         namelen = ident.name_end - ident.name_begin;
3677
3678         if (map_user(mailmap, &mail, &maillen, &name, &namelen)) {
3679                 struct strbuf namemail = STRBUF_INIT;
3680
3681                 strbuf_addf(&namemail, "%.*s <%.*s>",
3682                             (int)namelen, name, (int)maillen, mail);
3683
3684                 strbuf_splice(buf, ident.name_begin - buf->buf,
3685                               ident.mail_end - ident.name_begin + 1,
3686                               namemail.buf, namemail.len);
3687
3688                 strbuf_release(&namemail);
3689
3690                 return 1;
3691         }
3692
3693         return 0;
3694 }
3695
3696 static int commit_match(struct commit *commit, struct rev_info *opt)
3697 {
3698         int retval;
3699         const char *encoding;
3700         const char *message;
3701         struct strbuf buf = STRBUF_INIT;
3702
3703         if (!opt->grep_filter.pattern_list && !opt->grep_filter.header_list)
3704                 return 1;
3705
3706         /* Prepend "fake" headers as needed */
3707         if (opt->grep_filter.use_reflog_filter) {
3708                 strbuf_addstr(&buf, "reflog ");
3709                 get_reflog_message(&buf, opt->reflog_info);
3710                 strbuf_addch(&buf, '\n');
3711         }
3712
3713         /*
3714          * We grep in the user's output encoding, under the assumption that it
3715          * is the encoding they are most likely to write their grep pattern
3716          * for. In addition, it means we will match the "notes" encoding below,
3717          * so we will not end up with a buffer that has two different encodings
3718          * in it.
3719          */
3720         encoding = get_log_output_encoding();
3721         message = logmsg_reencode(commit, NULL, encoding);
3722
3723         /* Copy the commit to temporary if we are using "fake" headers */
3724         if (buf.len)
3725                 strbuf_addstr(&buf, message);
3726
3727         if (opt->grep_filter.header_list && opt->mailmap) {
3728                 if (!buf.len)
3729                         strbuf_addstr(&buf, message);
3730
3731                 commit_rewrite_person(&buf, "\nauthor ", opt->mailmap);
3732                 commit_rewrite_person(&buf, "\ncommitter ", opt->mailmap);
3733         }
3734
3735         /* Append "fake" message parts as needed */
3736         if (opt->show_notes) {
3737                 if (!buf.len)
3738                         strbuf_addstr(&buf, message);
3739                 format_display_notes(&commit->object.oid, &buf, encoding, 1);
3740         }
3741
3742         /*
3743          * Find either in the original commit message, or in the temporary.
3744          * Note that we cast away the constness of "message" here. It is
3745          * const because it may come from the cached commit buffer. That's OK,
3746          * because we know that it is modifiable heap memory, and that while
3747          * grep_buffer may modify it for speed, it will restore any
3748          * changes before returning.
3749          */
3750         if (buf.len)
3751                 retval = grep_buffer(&opt->grep_filter, buf.buf, buf.len);
3752         else
3753                 retval = grep_buffer(&opt->grep_filter,
3754                                      (char *)message, strlen(message));
3755         strbuf_release(&buf);
3756         unuse_commit_buffer(commit, message);
3757         return opt->invert_grep ? !retval : retval;
3758 }
3759
3760 static inline int want_ancestry(const struct rev_info *revs)
3761 {
3762         return (revs->rewrite_parents || revs->children.name);
3763 }
3764
3765 /*
3766  * Return a timestamp to be used for --since/--until comparisons for this
3767  * commit, based on the revision options.
3768  */
3769 static timestamp_t comparison_date(const struct rev_info *revs,
3770                                    struct commit *commit)
3771 {
3772         return revs->reflog_info ?
3773                 get_reflog_timestamp(revs->reflog_info) :
3774                 commit->date;
3775 }
3776
3777 enum commit_action get_commit_action(struct rev_info *revs, struct commit *commit)
3778 {
3779         if (commit->object.flags & SHOWN)
3780                 return commit_ignore;
3781         if (revs->unpacked && has_object_pack(&commit->object.oid))
3782                 return commit_ignore;
3783         if (commit->object.flags & UNINTERESTING)
3784                 return commit_ignore;
3785         if (revs->line_level_traverse && !want_ancestry(revs)) {
3786                 /*
3787                  * In case of line-level log with parent rewriting
3788                  * prepare_revision_walk() already took care of all line-level
3789                  * log filtering, and there is nothing left to do here.
3790                  *
3791                  * If parent rewriting was not requested, then this is the
3792                  * place to perform the line-level log filtering.  Notably,
3793                  * this check, though expensive, must come before the other,
3794                  * cheaper filtering conditions, because the tracked line
3795                  * ranges must be adjusted even when the commit will end up
3796                  * being ignored based on other conditions.
3797                  */
3798                 if (!line_log_process_ranges_arbitrary_commit(revs, commit))
3799                         return commit_ignore;
3800         }
3801         if (revs->min_age != -1 &&
3802             comparison_date(revs, commit) > revs->min_age)
3803                         return commit_ignore;
3804         if (revs->min_parents || (revs->max_parents >= 0)) {
3805                 int n = commit_list_count(commit->parents);
3806                 if ((n < revs->min_parents) ||
3807                     ((revs->max_parents >= 0) && (n > revs->max_parents)))
3808                         return commit_ignore;
3809         }
3810         if (!commit_match(commit, revs))
3811                 return commit_ignore;
3812         if (revs->prune && revs->dense) {
3813                 /* Commit without changes? */
3814                 if (commit->object.flags & TREESAME) {
3815                         int n;
3816                         struct commit_list *p;
3817                         /* drop merges unless we want parenthood */
3818                         if (!want_ancestry(revs))
3819                                 return commit_ignore;
3820
3821                         if (revs->show_pulls && (commit->object.flags & PULL_MERGE))
3822                                 return commit_show;
3823
3824                         /*
3825                          * If we want ancestry, then need to keep any merges
3826                          * between relevant commits to tie together topology.
3827                          * For consistency with TREESAME and simplification
3828                          * use "relevant" here rather than just INTERESTING,
3829                          * to treat bottom commit(s) as part of the topology.
3830                          */
3831                         for (n = 0, p = commit->parents; p; p = p->next)
3832                                 if (relevant_commit(p->item))
3833                                         if (++n >= 2)
3834                                                 return commit_show;
3835                         return commit_ignore;
3836                 }
3837         }
3838         return commit_show;
3839 }
3840
3841 define_commit_slab(saved_parents, struct commit_list *);
3842
3843 #define EMPTY_PARENT_LIST ((struct commit_list *)-1)
3844
3845 /*
3846  * You may only call save_parents() once per commit (this is checked
3847  * for non-root commits).
3848  */
3849 static void save_parents(struct rev_info *revs, struct commit *commit)
3850 {
3851         struct commit_list **pp;
3852
3853         if (!revs->saved_parents_slab) {
3854                 revs->saved_parents_slab = xmalloc(sizeof(struct saved_parents));
3855                 init_saved_parents(revs->saved_parents_slab);
3856         }
3857
3858         pp = saved_parents_at(revs->saved_parents_slab, commit);
3859
3860         /*
3861          * When walking with reflogs, we may visit the same commit
3862          * several times: once for each appearance in the reflog.
3863          *
3864          * In this case, save_parents() will be called multiple times.
3865          * We want to keep only the first set of parents.  We need to
3866          * store a sentinel value for an empty (i.e., NULL) parent
3867          * list to distinguish it from a not-yet-saved list, however.
3868          */
3869         if (*pp)
3870                 return;
3871         if (commit->parents)
3872                 *pp = copy_commit_list(commit->parents);
3873         else
3874                 *pp = EMPTY_PARENT_LIST;
3875 }
3876
3877 static void free_saved_parents(struct rev_info *revs)
3878 {
3879         if (revs->saved_parents_slab)
3880                 clear_saved_parents(revs->saved_parents_slab);
3881 }
3882
3883 struct commit_list *get_saved_parents(struct rev_info *revs, const struct commit *commit)
3884 {
3885         struct commit_list *parents;
3886
3887         if (!revs->saved_parents_slab)
3888                 return commit->parents;
3889
3890         parents = *saved_parents_at(revs->saved_parents_slab, commit);
3891         if (parents == EMPTY_PARENT_LIST)
3892                 return NULL;
3893         return parents;
3894 }
3895
3896 enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit)
3897 {
3898         enum commit_action action = get_commit_action(revs, commit);
3899
3900         if (action == commit_show &&
3901             revs->prune && revs->dense && want_ancestry(revs)) {
3902                 /*
3903                  * --full-diff on simplified parents is no good: it
3904                  * will show spurious changes from the commits that
3905                  * were elided.  So we save the parents on the side
3906                  * when --full-diff is in effect.
3907                  */
3908                 if (revs->full_diff)
3909                         save_parents(revs, commit);
3910                 if (rewrite_parents(revs, commit, rewrite_one) < 0)
3911                         return commit_error;
3912         }
3913         return action;
3914 }
3915
3916 static void track_linear(struct rev_info *revs, struct commit *commit)
3917 {
3918         if (revs->track_first_time) {
3919                 revs->linear = 1;
3920                 revs->track_first_time = 0;
3921         } else {
3922                 struct commit_list *p;
3923                 for (p = revs->previous_parents; p; p = p->next)
3924                         if (p->item == NULL || /* first commit */
3925                             oideq(&p->item->object.oid, &commit->object.oid))
3926                                 break;
3927                 revs->linear = p != NULL;
3928         }
3929         if (revs->reverse) {
3930                 if (revs->linear)
3931                         commit->object.flags |= TRACK_LINEAR;
3932         }
3933         free_commit_list(revs->previous_parents);
3934         revs->previous_parents = copy_commit_list(commit->parents);
3935 }
3936
3937 static struct commit *get_revision_1(struct rev_info *revs)
3938 {
3939         while (1) {
3940                 struct commit *commit;
3941
3942                 if (revs->reflog_info)
3943                         commit = next_reflog_entry(revs->reflog_info);
3944                 else if (revs->topo_walk_info)
3945                         commit = next_topo_commit(revs);
3946                 else
3947                         commit = pop_commit(&revs->commits);
3948
3949                 if (!commit)
3950                         return NULL;
3951
3952                 if (revs->reflog_info)
3953                         commit->object.flags &= ~(ADDED | SEEN | SHOWN);
3954
3955                 /*
3956                  * If we haven't done the list limiting, we need to look at
3957                  * the parents here. We also need to do the date-based limiting
3958                  * that we'd otherwise have done in limit_list().
3959                  */
3960                 if (!revs->limited) {
3961                         if (revs->max_age != -1 &&
3962                             comparison_date(revs, commit) < revs->max_age)
3963                                 continue;
3964
3965                         if (revs->reflog_info)
3966                                 try_to_simplify_commit(revs, commit);
3967                         else if (revs->topo_walk_info)
3968                                 expand_topo_walk(revs, commit);
3969                         else if (process_parents(revs, commit, &revs->commits, NULL) < 0) {
3970                                 if (!revs->ignore_missing_links)
3971                                         die("Failed to traverse parents of commit %s",
3972                                                 oid_to_hex(&commit->object.oid));
3973                         }
3974                 }
3975
3976                 switch (simplify_commit(revs, commit)) {
3977                 case commit_ignore:
3978                         continue;
3979                 case commit_error:
3980                         die("Failed to simplify parents of commit %s",
3981                             oid_to_hex(&commit->object.oid));
3982                 default:
3983                         if (revs->track_linear)
3984                                 track_linear(revs, commit);
3985                         return commit;
3986                 }
3987         }
3988 }
3989
3990 /*
3991  * Return true for entries that have not yet been shown.  (This is an
3992  * object_array_each_func_t.)
3993  */
3994 static int entry_unshown(struct object_array_entry *entry, void *cb_data_unused)
3995 {
3996         return !(entry->item->flags & SHOWN);
3997 }
3998
3999 /*
4000  * If array is on the verge of a realloc, garbage-collect any entries
4001  * that have already been shown to try to free up some space.
4002  */
4003 static void gc_boundary(struct object_array *array)
4004 {
4005         if (array->nr == array->alloc)
4006                 object_array_filter(array, entry_unshown, NULL);
4007 }
4008
4009 static void create_boundary_commit_list(struct rev_info *revs)
4010 {
4011         unsigned i;
4012         struct commit *c;
4013         struct object_array *array = &revs->boundary_commits;
4014         struct object_array_entry *objects = array->objects;
4015
4016         /*
4017          * If revs->commits is non-NULL at this point, an error occurred in
4018          * get_revision_1().  Ignore the error and continue printing the
4019          * boundary commits anyway.  (This is what the code has always
4020          * done.)
4021          */
4022         if (revs->commits) {
4023                 free_commit_list(revs->commits);
4024                 revs->commits = NULL;
4025         }
4026
4027         /*
4028          * Put all of the actual boundary commits from revs->boundary_commits
4029          * into revs->commits
4030          */
4031         for (i = 0; i < array->nr; i++) {
4032                 c = (struct commit *)(objects[i].item);
4033                 if (!c)
4034                         continue;
4035                 if (!(c->object.flags & CHILD_SHOWN))
4036                         continue;
4037                 if (c->object.flags & (SHOWN | BOUNDARY))
4038                         continue;
4039                 c->object.flags |= BOUNDARY;
4040                 commit_list_insert(c, &revs->commits);
4041         }
4042
4043         /*
4044          * If revs->topo_order is set, sort the boundary commits
4045          * in topological order
4046          */
4047         sort_in_topological_order(&revs->commits, revs->sort_order);
4048 }
4049
4050 static struct commit *get_revision_internal(struct rev_info *revs)
4051 {
4052         struct commit *c = NULL;
4053         struct commit_list *l;
4054
4055         if (revs->boundary == 2) {
4056                 /*
4057                  * All of the normal commits have already been returned,
4058                  * and we are now returning boundary commits.
4059                  * create_boundary_commit_list() has populated
4060                  * revs->commits with the remaining commits to return.
4061                  */
4062                 c = pop_commit(&revs->commits);
4063                 if (c)
4064                         c->object.flags |= SHOWN;
4065                 return c;
4066         }
4067
4068         /*
4069          * If our max_count counter has reached zero, then we are done. We
4070          * don't simply return NULL because we still might need to show
4071          * boundary commits. But we want to avoid calling get_revision_1, which
4072          * might do a considerable amount of work finding the next commit only
4073          * for us to throw it away.
4074          *
4075          * If it is non-zero, then either we don't have a max_count at all
4076          * (-1), or it is still counting, in which case we decrement.
4077          */
4078         if (revs->max_count) {
4079                 c = get_revision_1(revs);
4080                 if (c) {
4081                         while (revs->skip_count > 0) {
4082                                 revs->skip_count--;
4083                                 c = get_revision_1(revs);
4084                                 if (!c)
4085                                         break;
4086                         }
4087                 }
4088
4089                 if (revs->max_count > 0)
4090                         revs->max_count--;
4091         }
4092
4093         if (c)
4094                 c->object.flags |= SHOWN;
4095
4096         if (!revs->boundary)
4097                 return c;
4098
4099         if (!c) {
4100                 /*
4101                  * get_revision_1() runs out the commits, and
4102                  * we are done computing the boundaries.
4103                  * switch to boundary commits output mode.
4104                  */
4105                 revs->boundary = 2;
4106
4107                 /*
4108                  * Update revs->commits to contain the list of
4109                  * boundary commits.
4110                  */
4111                 create_boundary_commit_list(revs);
4112
4113                 return get_revision_internal(revs);
4114         }
4115
4116         /*
4117          * boundary commits are the commits that are parents of the
4118          * ones we got from get_revision_1() but they themselves are
4119          * not returned from get_revision_1().  Before returning
4120          * 'c', we need to mark its parents that they could be boundaries.
4121          */
4122
4123         for (l = c->parents; l; l = l->next) {
4124                 struct object *p;
4125                 p = &(l->item->object);
4126                 if (p->flags & (CHILD_SHOWN | SHOWN))
4127                         continue;
4128                 p->flags |= CHILD_SHOWN;
4129                 gc_boundary(&revs->boundary_commits);
4130                 add_object_array(p, NULL, &revs->boundary_commits);
4131         }
4132
4133         return c;
4134 }
4135
4136 struct commit *get_revision(struct rev_info *revs)
4137 {
4138         struct commit *c;
4139         struct commit_list *reversed;
4140
4141         if (revs->reverse) {
4142                 reversed = NULL;
4143                 while ((c = get_revision_internal(revs)))
4144                         commit_list_insert(c, &reversed);
4145                 revs->commits = reversed;
4146                 revs->reverse = 0;
4147                 revs->reverse_output_stage = 1;
4148         }
4149
4150         if (revs->reverse_output_stage) {
4151                 c = pop_commit(&revs->commits);
4152                 if (revs->track_linear)
4153                         revs->linear = !!(c && c->object.flags & TRACK_LINEAR);
4154                 return c;
4155         }
4156
4157         c = get_revision_internal(revs);
4158         if (c && revs->graph)
4159                 graph_update(revs->graph, c);
4160         if (!c) {
4161                 free_saved_parents(revs);
4162                 if (revs->previous_parents) {
4163                         free_commit_list(revs->previous_parents);
4164                         revs->previous_parents = NULL;
4165                 }
4166         }
4167         return c;
4168 }
4169
4170 const char *get_revision_mark(const struct rev_info *revs, const struct commit *commit)
4171 {
4172         if (commit->object.flags & BOUNDARY)
4173                 return "-";
4174         else if (commit->object.flags & UNINTERESTING)
4175                 return "^";
4176         else if (commit->object.flags & PATCHSAME)
4177                 return "=";
4178         else if (!revs || revs->left_right) {
4179                 if (commit->object.flags & SYMMETRIC_LEFT)
4180                         return "<";
4181                 else
4182                         return ">";
4183         } else if (revs->graph)
4184                 return "*";
4185         else if (revs->cherry_mark)
4186                 return "+";
4187         return "";
4188 }
4189
4190 void put_revision_mark(const struct rev_info *revs, const struct commit *commit)
4191 {
4192         const char *mark = get_revision_mark(revs, commit);
4193         if (!strlen(mark))
4194                 return;
4195         fputs(mark, stdout);
4196         putchar(' ');
4197 }