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