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