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