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