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