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