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