Fix revision walk for commits with the same dates
[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
17 volatile show_early_output_fn_t show_early_output;
18
19 char *path_name(const struct name_path *path, const char *name)
20 {
21         const struct name_path *p;
22         char *n, *m;
23         int nlen = strlen(name);
24         int len = nlen + 1;
25
26         for (p = path; p; p = p->up) {
27                 if (p->elem_len)
28                         len += p->elem_len + 1;
29         }
30         n = xmalloc(len);
31         m = n + len - (nlen + 1);
32         strcpy(m, name);
33         for (p = path; p; p = p->up) {
34                 if (p->elem_len) {
35                         m -= p->elem_len + 1;
36                         memcpy(m, p->elem, p->elem_len);
37                         m[p->elem_len] = '/';
38                 }
39         }
40         return n;
41 }
42
43 static int show_path_component_truncated(FILE *out, const char *name, int len)
44 {
45         int cnt;
46         for (cnt = 0; cnt < len; cnt++) {
47                 int ch = name[cnt];
48                 if (!ch || ch == '\n')
49                         return -1;
50                 fputc(ch, out);
51         }
52         return len;
53 }
54
55 static int show_path_truncated(FILE *out, const struct name_path *path)
56 {
57         int emitted, ours;
58
59         if (!path)
60                 return 0;
61         emitted = show_path_truncated(out, path->up);
62         if (emitted < 0)
63                 return emitted;
64         if (emitted)
65                 fputc('/', out);
66         ours = show_path_component_truncated(out, path->elem, path->elem_len);
67         if (ours < 0)
68                 return ours;
69         return ours || emitted;
70 }
71
72 void show_object_with_name(FILE *out, struct object *obj, const struct name_path *path, const char *component)
73 {
74         struct name_path leaf;
75         leaf.up = (struct name_path *)path;
76         leaf.elem = component;
77         leaf.elem_len = strlen(component);
78
79         fprintf(out, "%s ", sha1_to_hex(obj->sha1));
80         show_path_truncated(out, &leaf);
81         fputc('\n', out);
82 }
83
84 void add_object(struct object *obj,
85                 struct object_array *p,
86                 struct name_path *path,
87                 const char *name)
88 {
89         add_object_array(obj, path_name(path, name), p);
90 }
91
92 static void mark_blob_uninteresting(struct blob *blob)
93 {
94         if (!blob)
95                 return;
96         if (blob->object.flags & UNINTERESTING)
97                 return;
98         blob->object.flags |= UNINTERESTING;
99 }
100
101 void mark_tree_uninteresting(struct tree *tree)
102 {
103         struct tree_desc desc;
104         struct name_entry entry;
105         struct object *obj = &tree->object;
106
107         if (!tree)
108                 return;
109         if (obj->flags & UNINTERESTING)
110                 return;
111         obj->flags |= UNINTERESTING;
112         if (!has_sha1_file(obj->sha1))
113                 return;
114         if (parse_tree(tree) < 0)
115                 die("bad tree %s", sha1_to_hex(obj->sha1));
116
117         init_tree_desc(&desc, tree->buffer, tree->size);
118         while (tree_entry(&desc, &entry)) {
119                 switch (object_type(entry.mode)) {
120                 case OBJ_TREE:
121                         mark_tree_uninteresting(lookup_tree(entry.sha1));
122                         break;
123                 case OBJ_BLOB:
124                         mark_blob_uninteresting(lookup_blob(entry.sha1));
125                         break;
126                 default:
127                         /* Subproject commit - not in this repository */
128                         break;
129                 }
130         }
131
132         /*
133          * We don't care about the tree any more
134          * after it has been marked uninteresting.
135          */
136         free(tree->buffer);
137         tree->buffer = NULL;
138 }
139
140 void mark_parents_uninteresting(struct commit *commit)
141 {
142         struct commit_list *parents = NULL, *l;
143
144         for (l = commit->parents; l; l = l->next)
145                 commit_list_insert(l->item, &parents);
146
147         while (parents) {
148                 struct commit *commit = parents->item;
149                 l = parents;
150                 parents = parents->next;
151                 free(l);
152
153                 while (commit) {
154                         /*
155                          * A missing commit is ok iff its parent is marked
156                          * uninteresting.
157                          *
158                          * We just mark such a thing parsed, so that when
159                          * it is popped next time around, we won't be trying
160                          * to parse it and get an error.
161                          */
162                         if (!has_sha1_file(commit->object.sha1))
163                                 commit->object.parsed = 1;
164
165                         if (commit->object.flags & UNINTERESTING)
166                                 break;
167
168                         commit->object.flags |= UNINTERESTING;
169
170                         /*
171                          * Normally we haven't parsed the parent
172                          * yet, so we won't have a parent of a parent
173                          * here. However, it may turn out that we've
174                          * reached this commit some other way (where it
175                          * wasn't uninteresting), in which case we need
176                          * to mark its parents recursively too..
177                          */
178                         if (!commit->parents)
179                                 break;
180
181                         for (l = commit->parents->next; l; l = l->next)
182                                 commit_list_insert(l->item, &parents);
183                         commit = commit->parents->item;
184                 }
185         }
186 }
187
188 static void add_pending_object_with_mode(struct rev_info *revs, struct object *obj, const char *name, unsigned mode)
189 {
190         if (!obj)
191                 return;
192         if (revs->no_walk && (obj->flags & UNINTERESTING))
193                 revs->no_walk = 0;
194         if (revs->reflog_info && obj->type == OBJ_COMMIT) {
195                 struct strbuf buf = STRBUF_INIT;
196                 int len = interpret_branch_name(name, &buf);
197                 int st;
198
199                 if (0 < len && name[len] && buf.len)
200                         strbuf_addstr(&buf, name + len);
201                 st = add_reflog_for_walk(revs->reflog_info,
202                                          (struct commit *)obj,
203                                          buf.buf[0] ? buf.buf: name);
204                 strbuf_release(&buf);
205                 if (st)
206                         return;
207         }
208         add_object_array_with_mode(obj, name, &revs->pending, mode);
209 }
210
211 void add_pending_object(struct rev_info *revs, struct object *obj, const char *name)
212 {
213         add_pending_object_with_mode(revs, obj, name, S_IFINVALID);
214 }
215
216 void add_head_to_pending(struct rev_info *revs)
217 {
218         unsigned char sha1[20];
219         struct object *obj;
220         if (get_sha1("HEAD", sha1))
221                 return;
222         obj = parse_object(sha1);
223         if (!obj)
224                 return;
225         add_pending_object(revs, obj, "HEAD");
226 }
227
228 static struct object *get_reference(struct rev_info *revs, const char *name, const unsigned char *sha1, unsigned int flags)
229 {
230         struct object *object;
231
232         object = parse_object(sha1);
233         if (!object) {
234                 if (revs->ignore_missing)
235                         return object;
236                 die("bad object %s", name);
237         }
238         object->flags |= flags;
239         return object;
240 }
241
242 void add_pending_sha1(struct rev_info *revs, const char *name,
243                       const unsigned char *sha1, unsigned int flags)
244 {
245         struct object *object = get_reference(revs, name, sha1, flags);
246         add_pending_object(revs, object, name);
247 }
248
249 static struct commit *handle_commit(struct rev_info *revs, struct object *object, const char *name)
250 {
251         unsigned long flags = object->flags;
252
253         /*
254          * Tag object? Look what it points to..
255          */
256         while (object->type == OBJ_TAG) {
257                 struct tag *tag = (struct tag *) object;
258                 if (revs->tag_objects && !(flags & UNINTERESTING))
259                         add_pending_object(revs, object, tag->tag);
260                 if (!tag->tagged)
261                         die("bad tag");
262                 object = parse_object(tag->tagged->sha1);
263                 if (!object) {
264                         if (flags & UNINTERESTING)
265                                 return NULL;
266                         die("bad object %s", sha1_to_hex(tag->tagged->sha1));
267                 }
268         }
269
270         /*
271          * Commit object? Just return it, we'll do all the complex
272          * reachability crud.
273          */
274         if (object->type == OBJ_COMMIT) {
275                 struct commit *commit = (struct commit *)object;
276                 if (parse_commit(commit) < 0)
277                         die("unable to parse commit %s", name);
278                 if (flags & UNINTERESTING) {
279                         commit->object.flags |= UNINTERESTING;
280                         mark_parents_uninteresting(commit);
281                         revs->limited = 1;
282                 }
283                 if (revs->show_source && !commit->util)
284                         commit->util = (void *) name;
285                 return commit;
286         }
287
288         /*
289          * Tree object? Either mark it uninteresting, or add it
290          * to the list of objects to look at later..
291          */
292         if (object->type == OBJ_TREE) {
293                 struct tree *tree = (struct tree *)object;
294                 if (!revs->tree_objects)
295                         return NULL;
296                 if (flags & UNINTERESTING) {
297                         mark_tree_uninteresting(tree);
298                         return NULL;
299                 }
300                 add_pending_object(revs, object, "");
301                 return NULL;
302         }
303
304         /*
305          * Blob object? You know the drill by now..
306          */
307         if (object->type == OBJ_BLOB) {
308                 struct blob *blob = (struct blob *)object;
309                 if (!revs->blob_objects)
310                         return NULL;
311                 if (flags & UNINTERESTING) {
312                         mark_blob_uninteresting(blob);
313                         return NULL;
314                 }
315                 add_pending_object(revs, object, "");
316                 return NULL;
317         }
318         die("%s is unknown object", name);
319 }
320
321 static int everybody_uninteresting(struct commit_list *orig)
322 {
323         struct commit_list *list = orig;
324         while (list) {
325                 struct commit *commit = list->item;
326                 list = list->next;
327                 if (commit->object.flags & UNINTERESTING)
328                         continue;
329                 return 0;
330         }
331         return 1;
332 }
333
334 /*
335  * The goal is to get REV_TREE_NEW as the result only if the
336  * diff consists of all '+' (and no other changes), REV_TREE_OLD
337  * if the whole diff is removal of old data, and otherwise
338  * REV_TREE_DIFFERENT (of course if the trees are the same we
339  * want REV_TREE_SAME).
340  * That means that once we get to REV_TREE_DIFFERENT, we do not
341  * have to look any further.
342  */
343 static int tree_difference = REV_TREE_SAME;
344
345 static void file_add_remove(struct diff_options *options,
346                     int addremove, unsigned mode,
347                     const unsigned char *sha1,
348                     int sha1_valid,
349                     const char *fullpath, unsigned dirty_submodule)
350 {
351         int diff = addremove == '+' ? REV_TREE_NEW : REV_TREE_OLD;
352
353         tree_difference |= diff;
354         if (tree_difference == REV_TREE_DIFFERENT)
355                 DIFF_OPT_SET(options, HAS_CHANGES);
356 }
357
358 static void file_change(struct diff_options *options,
359                  unsigned old_mode, unsigned new_mode,
360                  const unsigned char *old_sha1,
361                  const unsigned char *new_sha1,
362                  int old_sha1_valid, int new_sha1_valid,
363                  const char *fullpath,
364                  unsigned old_dirty_submodule, unsigned new_dirty_submodule)
365 {
366         tree_difference = REV_TREE_DIFFERENT;
367         DIFF_OPT_SET(options, HAS_CHANGES);
368 }
369
370 static int rev_compare_tree(struct rev_info *revs, struct commit *parent, struct commit *commit)
371 {
372         struct tree *t1 = parent->tree;
373         struct tree *t2 = commit->tree;
374
375         if (!t1)
376                 return REV_TREE_NEW;
377         if (!t2)
378                 return REV_TREE_OLD;
379
380         if (revs->simplify_by_decoration) {
381                 /*
382                  * If we are simplifying by decoration, then the commit
383                  * is worth showing if it has a tag pointing at it.
384                  */
385                 if (lookup_decoration(&name_decoration, &commit->object))
386                         return REV_TREE_DIFFERENT;
387                 /*
388                  * A commit that is not pointed by a tag is uninteresting
389                  * if we are not limited by path.  This means that you will
390                  * see the usual "commits that touch the paths" plus any
391                  * tagged commit by specifying both --simplify-by-decoration
392                  * and pathspec.
393                  */
394                 if (!revs->prune_data.nr)
395                         return REV_TREE_SAME;
396         }
397
398         tree_difference = REV_TREE_SAME;
399         DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
400         if (diff_tree_sha1(t1->object.sha1, t2->object.sha1, "",
401                            &revs->pruning) < 0)
402                 return REV_TREE_DIFFERENT;
403         return tree_difference;
404 }
405
406 static int rev_same_tree_as_empty(struct rev_info *revs, struct commit *commit)
407 {
408         int retval;
409         void *tree;
410         unsigned long size;
411         struct tree_desc empty, real;
412         struct tree *t1 = commit->tree;
413
414         if (!t1)
415                 return 0;
416
417         tree = read_object_with_reference(t1->object.sha1, tree_type, &size, NULL);
418         if (!tree)
419                 return 0;
420         init_tree_desc(&real, tree, size);
421         init_tree_desc(&empty, "", 0);
422
423         tree_difference = REV_TREE_SAME;
424         DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
425         retval = diff_tree(&empty, &real, "", &revs->pruning);
426         free(tree);
427
428         return retval >= 0 && (tree_difference == REV_TREE_SAME);
429 }
430
431 static void try_to_simplify_commit(struct rev_info *revs, struct commit *commit)
432 {
433         struct commit_list **pp, *parent;
434         int tree_changed = 0, tree_same = 0, nth_parent = 0;
435
436         /*
437          * If we don't do pruning, everything is interesting
438          */
439         if (!revs->prune)
440                 return;
441
442         if (!commit->tree)
443                 return;
444
445         if (!commit->parents) {
446                 if (rev_same_tree_as_empty(revs, commit))
447                         commit->object.flags |= TREESAME;
448                 return;
449         }
450
451         /*
452          * Normal non-merge commit? If we don't want to make the
453          * history dense, we consider it always to be a change..
454          */
455         if (!revs->dense && !commit->parents->next)
456                 return;
457
458         pp = &commit->parents;
459         while ((parent = *pp) != NULL) {
460                 struct commit *p = parent->item;
461
462                 /*
463                  * Do not compare with later parents when we care only about
464                  * the first parent chain, in order to avoid derailing the
465                  * traversal to follow a side branch that brought everything
466                  * in the path we are limited to by the pathspec.
467                  */
468                 if (revs->first_parent_only && nth_parent++)
469                         break;
470                 if (parse_commit(p) < 0)
471                         die("cannot simplify commit %s (because of %s)",
472                             sha1_to_hex(commit->object.sha1),
473                             sha1_to_hex(p->object.sha1));
474                 switch (rev_compare_tree(revs, p, commit)) {
475                 case REV_TREE_SAME:
476                         tree_same = 1;
477                         if (!revs->simplify_history || (p->object.flags & UNINTERESTING)) {
478                                 /* Even if a merge with an uninteresting
479                                  * side branch brought the entire change
480                                  * we are interested in, we do not want
481                                  * to lose the other branches of this
482                                  * merge, so we just keep going.
483                                  */
484                                 pp = &parent->next;
485                                 continue;
486                         }
487                         parent->next = NULL;
488                         commit->parents = parent;
489                         commit->object.flags |= TREESAME;
490                         return;
491
492                 case REV_TREE_NEW:
493                         if (revs->remove_empty_trees &&
494                             rev_same_tree_as_empty(revs, p)) {
495                                 /* We are adding all the specified
496                                  * paths from this parent, so the
497                                  * history beyond this parent is not
498                                  * interesting.  Remove its parents
499                                  * (they are grandparents for us).
500                                  * IOW, we pretend this parent is a
501                                  * "root" commit.
502                                  */
503                                 if (parse_commit(p) < 0)
504                                         die("cannot simplify commit %s (invalid %s)",
505                                             sha1_to_hex(commit->object.sha1),
506                                             sha1_to_hex(p->object.sha1));
507                                 p->parents = NULL;
508                         }
509                 /* fallthrough */
510                 case REV_TREE_OLD:
511                 case REV_TREE_DIFFERENT:
512                         tree_changed = 1;
513                         pp = &parent->next;
514                         continue;
515                 }
516                 die("bad tree compare for commit %s", sha1_to_hex(commit->object.sha1));
517         }
518         if (tree_changed && !tree_same)
519                 return;
520         commit->object.flags |= TREESAME;
521 }
522
523 static void commit_list_insert_by_date_cached(struct commit *p, struct commit_list **head,
524                     struct commit_list *cached_base, struct commit_list **cache)
525 {
526         struct commit_list *new_entry;
527
528         if (cached_base && p->date < cached_base->item->date)
529                 new_entry = commit_list_insert_by_date(p, &cached_base->next);
530         else
531                 new_entry = commit_list_insert_by_date(p, head);
532
533         if (cache && (!*cache || p->date < (*cache)->item->date))
534                 *cache = new_entry;
535 }
536
537 static int add_parents_to_list(struct rev_info *revs, struct commit *commit,
538                     struct commit_list **list, struct commit_list **cache_ptr)
539 {
540         struct commit_list *parent = commit->parents;
541         unsigned left_flag;
542         struct commit_list *cached_base = cache_ptr ? *cache_ptr : NULL;
543
544         if (commit->object.flags & ADDED)
545                 return 0;
546         commit->object.flags |= ADDED;
547
548         /*
549          * If the commit is uninteresting, don't try to
550          * prune parents - we want the maximal uninteresting
551          * set.
552          *
553          * Normally we haven't parsed the parent
554          * yet, so we won't have a parent of a parent
555          * here. However, it may turn out that we've
556          * reached this commit some other way (where it
557          * wasn't uninteresting), in which case we need
558          * to mark its parents recursively too..
559          */
560         if (commit->object.flags & UNINTERESTING) {
561                 while (parent) {
562                         struct commit *p = parent->item;
563                         parent = parent->next;
564                         if (p)
565                                 p->object.flags |= UNINTERESTING;
566                         if (parse_commit(p) < 0)
567                                 continue;
568                         if (p->parents)
569                                 mark_parents_uninteresting(p);
570                         if (p->object.flags & SEEN)
571                                 continue;
572                         p->object.flags |= SEEN;
573                         commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
574                 }
575                 return 0;
576         }
577
578         /*
579          * Ok, the commit wasn't uninteresting. Try to
580          * simplify the commit history and find the parent
581          * that has no differences in the path set if one exists.
582          */
583         try_to_simplify_commit(revs, commit);
584
585         if (revs->no_walk)
586                 return 0;
587
588         left_flag = (commit->object.flags & SYMMETRIC_LEFT);
589
590         for (parent = commit->parents; parent; parent = parent->next) {
591                 struct commit *p = parent->item;
592
593                 if (parse_commit(p) < 0)
594                         return -1;
595                 if (revs->show_source && !p->util)
596                         p->util = commit->util;
597                 p->object.flags |= left_flag;
598                 if (!(p->object.flags & SEEN)) {
599                         p->object.flags |= SEEN;
600                         commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
601                 }
602                 if (revs->first_parent_only)
603                         break;
604         }
605         return 0;
606 }
607
608 static void cherry_pick_list(struct commit_list *list, struct rev_info *revs)
609 {
610         struct commit_list *p;
611         int left_count = 0, right_count = 0;
612         int left_first;
613         struct patch_ids ids;
614         unsigned cherry_flag;
615
616         /* First count the commits on the left and on the right */
617         for (p = list; p; p = p->next) {
618                 struct commit *commit = p->item;
619                 unsigned flags = commit->object.flags;
620                 if (flags & BOUNDARY)
621                         ;
622                 else if (flags & SYMMETRIC_LEFT)
623                         left_count++;
624                 else
625                         right_count++;
626         }
627
628         if (!left_count || !right_count)
629                 return;
630
631         left_first = left_count < right_count;
632         init_patch_ids(&ids);
633         ids.diffopts.pathspec = revs->diffopt.pathspec;
634
635         /* Compute patch-ids for one side */
636         for (p = list; p; p = p->next) {
637                 struct commit *commit = p->item;
638                 unsigned flags = commit->object.flags;
639
640                 if (flags & BOUNDARY)
641                         continue;
642                 /*
643                  * If we have fewer left, left_first is set and we omit
644                  * commits on the right branch in this loop.  If we have
645                  * fewer right, we skip the left ones.
646                  */
647                 if (left_first != !!(flags & SYMMETRIC_LEFT))
648                         continue;
649                 commit->util = add_commit_patch_id(commit, &ids);
650         }
651
652         /* either cherry_mark or cherry_pick are true */
653         cherry_flag = revs->cherry_mark ? PATCHSAME : SHOWN;
654
655         /* Check the other side */
656         for (p = list; p; p = p->next) {
657                 struct commit *commit = p->item;
658                 struct patch_id *id;
659                 unsigned flags = commit->object.flags;
660
661                 if (flags & BOUNDARY)
662                         continue;
663                 /*
664                  * If we have fewer left, left_first is set and we omit
665                  * commits on the left branch in this loop.
666                  */
667                 if (left_first == !!(flags & SYMMETRIC_LEFT))
668                         continue;
669
670                 /*
671                  * Have we seen the same patch id?
672                  */
673                 id = has_commit_patch_id(commit, &ids);
674                 if (!id)
675                         continue;
676                 id->seen = 1;
677                 commit->object.flags |= cherry_flag;
678         }
679
680         /* Now check the original side for seen ones */
681         for (p = list; p; p = p->next) {
682                 struct commit *commit = p->item;
683                 struct patch_id *ent;
684
685                 ent = commit->util;
686                 if (!ent)
687                         continue;
688                 if (ent->seen)
689                         commit->object.flags |= cherry_flag;
690                 commit->util = NULL;
691         }
692
693         free_patch_ids(&ids);
694 }
695
696 /* How many extra uninteresting commits we want to see.. */
697 #define SLOP 5
698
699 static int still_interesting(struct commit_list *src, unsigned long date, int slop)
700 {
701         /*
702          * No source list at all? We're definitely done..
703          */
704         if (!src)
705                 return 0;
706
707         /*
708          * Does the destination list contain entries with a date
709          * before the source list? Definitely _not_ done.
710          */
711         if (date <= src->item->date)
712                 return SLOP;
713
714         /*
715          * Does the source list still have interesting commits in
716          * it? Definitely not done..
717          */
718         if (!everybody_uninteresting(src))
719                 return SLOP;
720
721         /* Ok, we're closing in.. */
722         return slop-1;
723 }
724
725 /*
726  * "rev-list --ancestry-path A..B" computes commits that are ancestors
727  * of B but not ancestors of A but further limits the result to those
728  * that are descendants of A.  This takes the list of bottom commits and
729  * the result of "A..B" without --ancestry-path, and limits the latter
730  * further to the ones that can reach one of the commits in "bottom".
731  */
732 static void limit_to_ancestry(struct commit_list *bottom, struct commit_list *list)
733 {
734         struct commit_list *p;
735         struct commit_list *rlist = NULL;
736         int made_progress;
737
738         /*
739          * Reverse the list so that it will be likely that we would
740          * process parents before children.
741          */
742         for (p = list; p; p = p->next)
743                 commit_list_insert(p->item, &rlist);
744
745         for (p = bottom; p; p = p->next)
746                 p->item->object.flags |= TMP_MARK;
747
748         /*
749          * Mark the ones that can reach bottom commits in "list",
750          * in a bottom-up fashion.
751          */
752         do {
753                 made_progress = 0;
754                 for (p = rlist; p; p = p->next) {
755                         struct commit *c = p->item;
756                         struct commit_list *parents;
757                         if (c->object.flags & (TMP_MARK | UNINTERESTING))
758                                 continue;
759                         for (parents = c->parents;
760                              parents;
761                              parents = parents->next) {
762                                 if (!(parents->item->object.flags & TMP_MARK))
763                                         continue;
764                                 c->object.flags |= TMP_MARK;
765                                 made_progress = 1;
766                                 break;
767                         }
768                 }
769         } while (made_progress);
770
771         /*
772          * NEEDSWORK: decide if we want to remove parents that are
773          * not marked with TMP_MARK from commit->parents for commits
774          * in the resulting list.  We may not want to do that, though.
775          */
776
777         /*
778          * The ones that are not marked with TMP_MARK are uninteresting
779          */
780         for (p = list; p; p = p->next) {
781                 struct commit *c = p->item;
782                 if (c->object.flags & TMP_MARK)
783                         continue;
784                 c->object.flags |= UNINTERESTING;
785         }
786
787         /* We are done with the TMP_MARK */
788         for (p = list; p; p = p->next)
789                 p->item->object.flags &= ~TMP_MARK;
790         for (p = bottom; p; p = p->next)
791                 p->item->object.flags &= ~TMP_MARK;
792         free_commit_list(rlist);
793 }
794
795 /*
796  * Before walking the history, keep the set of "negative" refs the
797  * caller has asked to exclude.
798  *
799  * This is used to compute "rev-list --ancestry-path A..B", as we need
800  * to filter the result of "A..B" further to the ones that can actually
801  * reach A.
802  */
803 static struct commit_list *collect_bottom_commits(struct rev_info *revs)
804 {
805         struct commit_list *bottom = NULL;
806         int i;
807         for (i = 0; i < revs->cmdline.nr; i++) {
808                 struct rev_cmdline_entry *elem = &revs->cmdline.rev[i];
809                 if ((elem->flags & UNINTERESTING) &&
810                     elem->item->type == OBJ_COMMIT)
811                         commit_list_insert((struct commit *)elem->item, &bottom);
812         }
813         return bottom;
814 }
815
816 /* Assumes either left_only or right_only is set */
817 static void limit_left_right(struct commit_list *list, struct rev_info *revs)
818 {
819         struct commit_list *p;
820
821         for (p = list; p; p = p->next) {
822                 struct commit *commit = p->item;
823
824                 if (revs->right_only) {
825                         if (commit->object.flags & SYMMETRIC_LEFT)
826                                 commit->object.flags |= SHOWN;
827                 } else  /* revs->left_only is set */
828                         if (!(commit->object.flags & SYMMETRIC_LEFT))
829                                 commit->object.flags |= SHOWN;
830         }
831 }
832
833 static int limit_list(struct rev_info *revs)
834 {
835         int slop = SLOP;
836         unsigned long date = ~0ul;
837         struct commit_list *list = revs->commits;
838         struct commit_list *newlist = NULL;
839         struct commit_list **p = &newlist;
840         struct commit_list *bottom = NULL;
841
842         if (revs->ancestry_path) {
843                 bottom = collect_bottom_commits(revs);
844                 if (!bottom)
845                         die("--ancestry-path given but there are no bottom commits");
846         }
847
848         while (list) {
849                 struct commit_list *entry = list;
850                 struct commit *commit = list->item;
851                 struct object *obj = &commit->object;
852                 show_early_output_fn_t show;
853
854                 list = list->next;
855                 free(entry);
856
857                 if (revs->max_age != -1 && (commit->date < revs->max_age))
858                         obj->flags |= UNINTERESTING;
859                 if (add_parents_to_list(revs, commit, &list, NULL) < 0)
860                         return -1;
861                 if (obj->flags & UNINTERESTING) {
862                         mark_parents_uninteresting(commit);
863                         if (revs->show_all)
864                                 p = &commit_list_insert(commit, p)->next;
865                         slop = still_interesting(list, date, slop);
866                         if (slop)
867                                 continue;
868                         /* If showing all, add the whole pending list to the end */
869                         if (revs->show_all)
870                                 *p = list;
871                         break;
872                 }
873                 if (revs->min_age != -1 && (commit->date > revs->min_age))
874                         continue;
875                 date = commit->date;
876                 p = &commit_list_insert(commit, p)->next;
877
878                 show = show_early_output;
879                 if (!show)
880                         continue;
881
882                 show(revs, newlist);
883                 show_early_output = NULL;
884         }
885         if (revs->cherry_pick || revs->cherry_mark)
886                 cherry_pick_list(newlist, revs);
887
888         if (revs->left_only || revs->right_only)
889                 limit_left_right(newlist, revs);
890
891         if (bottom) {
892                 limit_to_ancestry(bottom, newlist);
893                 free_commit_list(bottom);
894         }
895
896         revs->commits = newlist;
897         return 0;
898 }
899
900 static void add_rev_cmdline(struct rev_info *revs,
901                             struct object *item,
902                             const char *name,
903                             int whence,
904                             unsigned flags)
905 {
906         struct rev_cmdline_info *info = &revs->cmdline;
907         int nr = info->nr;
908
909         ALLOC_GROW(info->rev, nr + 1, info->alloc);
910         info->rev[nr].item = item;
911         info->rev[nr].name = name;
912         info->rev[nr].whence = whence;
913         info->rev[nr].flags = flags;
914         info->nr++;
915 }
916
917 struct all_refs_cb {
918         int all_flags;
919         int warned_bad_reflog;
920         struct rev_info *all_revs;
921         const char *name_for_errormsg;
922 };
923
924 static int handle_one_ref(const char *path, const unsigned char *sha1, int flag, void *cb_data)
925 {
926         struct all_refs_cb *cb = cb_data;
927         struct object *object = get_reference(cb->all_revs, path, sha1,
928                                               cb->all_flags);
929         add_rev_cmdline(cb->all_revs, object, path, REV_CMD_REF, cb->all_flags);
930         add_pending_sha1(cb->all_revs, path, sha1, cb->all_flags);
931         return 0;
932 }
933
934 static void init_all_refs_cb(struct all_refs_cb *cb, struct rev_info *revs,
935         unsigned flags)
936 {
937         cb->all_revs = revs;
938         cb->all_flags = flags;
939 }
940
941 static void handle_refs(const char *submodule, struct rev_info *revs, unsigned flags,
942                 int (*for_each)(const char *, each_ref_fn, void *))
943 {
944         struct all_refs_cb cb;
945         init_all_refs_cb(&cb, revs, flags);
946         for_each(submodule, handle_one_ref, &cb);
947 }
948
949 static void handle_one_reflog_commit(unsigned char *sha1, void *cb_data)
950 {
951         struct all_refs_cb *cb = cb_data;
952         if (!is_null_sha1(sha1)) {
953                 struct object *o = parse_object(sha1);
954                 if (o) {
955                         o->flags |= cb->all_flags;
956                         /* ??? CMDLINEFLAGS ??? */
957                         add_pending_object(cb->all_revs, o, "");
958                 }
959                 else if (!cb->warned_bad_reflog) {
960                         warning("reflog of '%s' references pruned commits",
961                                 cb->name_for_errormsg);
962                         cb->warned_bad_reflog = 1;
963                 }
964         }
965 }
966
967 static int handle_one_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
968                 const char *email, unsigned long timestamp, int tz,
969                 const char *message, void *cb_data)
970 {
971         handle_one_reflog_commit(osha1, cb_data);
972         handle_one_reflog_commit(nsha1, cb_data);
973         return 0;
974 }
975
976 static int handle_one_reflog(const char *path, const unsigned char *sha1, int flag, void *cb_data)
977 {
978         struct all_refs_cb *cb = cb_data;
979         cb->warned_bad_reflog = 0;
980         cb->name_for_errormsg = path;
981         for_each_reflog_ent(path, handle_one_reflog_ent, cb_data);
982         return 0;
983 }
984
985 static void handle_reflog(struct rev_info *revs, unsigned flags)
986 {
987         struct all_refs_cb cb;
988         cb.all_revs = revs;
989         cb.all_flags = flags;
990         for_each_reflog(handle_one_reflog, &cb);
991 }
992
993 static int add_parents_only(struct rev_info *revs, const char *arg_, int flags)
994 {
995         unsigned char sha1[20];
996         struct object *it;
997         struct commit *commit;
998         struct commit_list *parents;
999         const char *arg = arg_;
1000
1001         if (*arg == '^') {
1002                 flags ^= UNINTERESTING;
1003                 arg++;
1004         }
1005         if (get_sha1_committish(arg, sha1))
1006                 return 0;
1007         while (1) {
1008                 it = get_reference(revs, arg, sha1, 0);
1009                 if (!it && revs->ignore_missing)
1010                         return 0;
1011                 if (it->type != OBJ_TAG)
1012                         break;
1013                 if (!((struct tag*)it)->tagged)
1014                         return 0;
1015                 hashcpy(sha1, ((struct tag*)it)->tagged->sha1);
1016         }
1017         if (it->type != OBJ_COMMIT)
1018                 return 0;
1019         commit = (struct commit *)it;
1020         for (parents = commit->parents; parents; parents = parents->next) {
1021                 it = &parents->item->object;
1022                 it->flags |= flags;
1023                 add_rev_cmdline(revs, it, arg_, REV_CMD_PARENTS_ONLY, flags);
1024                 add_pending_object(revs, it, arg);
1025         }
1026         return 1;
1027 }
1028
1029 void init_revisions(struct rev_info *revs, const char *prefix)
1030 {
1031         memset(revs, 0, sizeof(*revs));
1032
1033         revs->abbrev = DEFAULT_ABBREV;
1034         revs->ignore_merges = 1;
1035         revs->simplify_history = 1;
1036         DIFF_OPT_SET(&revs->pruning, RECURSIVE);
1037         DIFF_OPT_SET(&revs->pruning, QUICK);
1038         revs->pruning.add_remove = file_add_remove;
1039         revs->pruning.change = file_change;
1040         revs->lifo = 1;
1041         revs->dense = 1;
1042         revs->prefix = prefix;
1043         revs->max_age = -1;
1044         revs->min_age = -1;
1045         revs->skip_count = -1;
1046         revs->max_count = -1;
1047         revs->max_parents = -1;
1048
1049         revs->commit_format = CMIT_FMT_DEFAULT;
1050
1051         init_grep_defaults();
1052         grep_init(&revs->grep_filter, prefix);
1053         revs->grep_filter.status_only = 1;
1054         revs->grep_filter.regflags = REG_NEWLINE;
1055
1056         diff_setup(&revs->diffopt);
1057         if (prefix && !revs->diffopt.prefix) {
1058                 revs->diffopt.prefix = prefix;
1059                 revs->diffopt.prefix_length = strlen(prefix);
1060         }
1061
1062         revs->notes_opt.use_default_notes = -1;
1063 }
1064
1065 static void add_pending_commit_list(struct rev_info *revs,
1066                                     struct commit_list *commit_list,
1067                                     unsigned int flags)
1068 {
1069         while (commit_list) {
1070                 struct object *object = &commit_list->item->object;
1071                 object->flags |= flags;
1072                 add_pending_object(revs, object, sha1_to_hex(object->sha1));
1073                 commit_list = commit_list->next;
1074         }
1075 }
1076
1077 static void prepare_show_merge(struct rev_info *revs)
1078 {
1079         struct commit_list *bases;
1080         struct commit *head, *other;
1081         unsigned char sha1[20];
1082         const char **prune = NULL;
1083         int i, prune_num = 1; /* counting terminating NULL */
1084
1085         if (get_sha1("HEAD", sha1))
1086                 die("--merge without HEAD?");
1087         head = lookup_commit_or_die(sha1, "HEAD");
1088         if (get_sha1("MERGE_HEAD", sha1))
1089                 die("--merge without MERGE_HEAD?");
1090         other = lookup_commit_or_die(sha1, "MERGE_HEAD");
1091         add_pending_object(revs, &head->object, "HEAD");
1092         add_pending_object(revs, &other->object, "MERGE_HEAD");
1093         bases = get_merge_bases(head, other, 1);
1094         add_pending_commit_list(revs, bases, UNINTERESTING);
1095         free_commit_list(bases);
1096         head->object.flags |= SYMMETRIC_LEFT;
1097
1098         if (!active_nr)
1099                 read_cache();
1100         for (i = 0; i < active_nr; i++) {
1101                 struct cache_entry *ce = active_cache[i];
1102                 if (!ce_stage(ce))
1103                         continue;
1104                 if (ce_path_match(ce, &revs->prune_data)) {
1105                         prune_num++;
1106                         prune = xrealloc(prune, sizeof(*prune) * prune_num);
1107                         prune[prune_num-2] = ce->name;
1108                         prune[prune_num-1] = NULL;
1109                 }
1110                 while ((i+1 < active_nr) &&
1111                        ce_same_name(ce, active_cache[i+1]))
1112                         i++;
1113         }
1114         free_pathspec(&revs->prune_data);
1115         init_pathspec(&revs->prune_data, prune);
1116         revs->limited = 1;
1117 }
1118
1119 int handle_revision_arg(const char *arg_, struct rev_info *revs, int flags, unsigned revarg_opt)
1120 {
1121         struct object_context oc;
1122         char *dotdot;
1123         struct object *object;
1124         unsigned char sha1[20];
1125         int local_flags;
1126         const char *arg = arg_;
1127         int cant_be_filename = revarg_opt & REVARG_CANNOT_BE_FILENAME;
1128         unsigned get_sha1_flags = 0;
1129
1130         dotdot = strstr(arg, "..");
1131         if (dotdot) {
1132                 unsigned char from_sha1[20];
1133                 const char *next = dotdot + 2;
1134                 const char *this = arg;
1135                 int symmetric = *next == '.';
1136                 unsigned int flags_exclude = flags ^ UNINTERESTING;
1137                 static const char head_by_default[] = "HEAD";
1138                 unsigned int a_flags;
1139
1140                 *dotdot = 0;
1141                 next += symmetric;
1142
1143                 if (!*next)
1144                         next = head_by_default;
1145                 if (dotdot == arg)
1146                         this = head_by_default;
1147                 if (this == head_by_default && next == head_by_default &&
1148                     !symmetric) {
1149                         /*
1150                          * Just ".."?  That is not a range but the
1151                          * pathspec for the parent directory.
1152                          */
1153                         if (!cant_be_filename) {
1154                                 *dotdot = '.';
1155                                 return -1;
1156                         }
1157                 }
1158                 if (!get_sha1_committish(this, from_sha1) &&
1159                     !get_sha1_committish(next, sha1)) {
1160                         struct commit *a, *b;
1161                         struct commit_list *exclude;
1162
1163                         a = lookup_commit_reference(from_sha1);
1164                         b = lookup_commit_reference(sha1);
1165                         if (!a || !b) {
1166                                 if (revs->ignore_missing)
1167                                         return 0;
1168                                 die(symmetric ?
1169                                     "Invalid symmetric difference expression %s...%s" :
1170                                     "Invalid revision range %s..%s",
1171                                     arg, next);
1172                         }
1173
1174                         if (!cant_be_filename) {
1175                                 *dotdot = '.';
1176                                 verify_non_filename(revs->prefix, arg);
1177                         }
1178
1179                         if (symmetric) {
1180                                 exclude = get_merge_bases(a, b, 1);
1181                                 add_pending_commit_list(revs, exclude,
1182                                                         flags_exclude);
1183                                 free_commit_list(exclude);
1184                                 a_flags = flags | SYMMETRIC_LEFT;
1185                         } else
1186                                 a_flags = flags_exclude;
1187                         a->object.flags |= a_flags;
1188                         b->object.flags |= flags;
1189                         add_rev_cmdline(revs, &a->object, this,
1190                                         REV_CMD_LEFT, a_flags);
1191                         add_rev_cmdline(revs, &b->object, next,
1192                                         REV_CMD_RIGHT, flags);
1193                         add_pending_object(revs, &a->object, this);
1194                         add_pending_object(revs, &b->object, next);
1195                         return 0;
1196                 }
1197                 *dotdot = '.';
1198         }
1199         dotdot = strstr(arg, "^@");
1200         if (dotdot && !dotdot[2]) {
1201                 *dotdot = 0;
1202                 if (add_parents_only(revs, arg, flags))
1203                         return 0;
1204                 *dotdot = '^';
1205         }
1206         dotdot = strstr(arg, "^!");
1207         if (dotdot && !dotdot[2]) {
1208                 *dotdot = 0;
1209                 if (!add_parents_only(revs, arg, flags ^ UNINTERESTING))
1210                         *dotdot = '^';
1211         }
1212
1213         local_flags = 0;
1214         if (*arg == '^') {
1215                 local_flags = UNINTERESTING;
1216                 arg++;
1217         }
1218
1219         if (revarg_opt & REVARG_COMMITTISH)
1220                 get_sha1_flags = GET_SHA1_COMMITTISH;
1221
1222         if (get_sha1_with_context(arg, get_sha1_flags, sha1, &oc))
1223                 return revs->ignore_missing ? 0 : -1;
1224         if (!cant_be_filename)
1225                 verify_non_filename(revs->prefix, arg);
1226         object = get_reference(revs, arg, sha1, flags ^ local_flags);
1227         add_rev_cmdline(revs, object, arg_, REV_CMD_REV, flags ^ local_flags);
1228         add_pending_object_with_mode(revs, object, arg, oc.mode);
1229         return 0;
1230 }
1231
1232 struct cmdline_pathspec {
1233         int alloc;
1234         int nr;
1235         const char **path;
1236 };
1237
1238 static void append_prune_data(struct cmdline_pathspec *prune, const char **av)
1239 {
1240         while (*av) {
1241                 ALLOC_GROW(prune->path, prune->nr+1, prune->alloc);
1242                 prune->path[prune->nr++] = *(av++);
1243         }
1244 }
1245
1246 static void read_pathspec_from_stdin(struct rev_info *revs, struct strbuf *sb,
1247                                      struct cmdline_pathspec *prune)
1248 {
1249         while (strbuf_getwholeline(sb, stdin, '\n') != EOF) {
1250                 int len = sb->len;
1251                 if (len && sb->buf[len - 1] == '\n')
1252                         sb->buf[--len] = '\0';
1253                 ALLOC_GROW(prune->path, prune->nr+1, prune->alloc);
1254                 prune->path[prune->nr++] = xstrdup(sb->buf);
1255         }
1256 }
1257
1258 static void read_revisions_from_stdin(struct rev_info *revs,
1259                                       struct cmdline_pathspec *prune)
1260 {
1261         struct strbuf sb;
1262         int seen_dashdash = 0;
1263
1264         strbuf_init(&sb, 1000);
1265         while (strbuf_getwholeline(&sb, stdin, '\n') != EOF) {
1266                 int len = sb.len;
1267                 if (len && sb.buf[len - 1] == '\n')
1268                         sb.buf[--len] = '\0';
1269                 if (!len)
1270                         break;
1271                 if (sb.buf[0] == '-') {
1272                         if (len == 2 && sb.buf[1] == '-') {
1273                                 seen_dashdash = 1;
1274                                 break;
1275                         }
1276                         die("options not supported in --stdin mode");
1277                 }
1278                 if (handle_revision_arg(sb.buf, revs, 0, REVARG_CANNOT_BE_FILENAME))
1279                         die("bad revision '%s'", sb.buf);
1280         }
1281         if (seen_dashdash)
1282                 read_pathspec_from_stdin(revs, &sb, prune);
1283         strbuf_release(&sb);
1284 }
1285
1286 static void add_grep(struct rev_info *revs, const char *ptn, enum grep_pat_token what)
1287 {
1288         append_grep_pattern(&revs->grep_filter, ptn, "command line", 0, what);
1289 }
1290
1291 static void add_header_grep(struct rev_info *revs, enum grep_header_field field, const char *pattern)
1292 {
1293         append_header_grep_pattern(&revs->grep_filter, field, pattern);
1294 }
1295
1296 static void add_message_grep(struct rev_info *revs, const char *pattern)
1297 {
1298         add_grep(revs, pattern, GREP_PATTERN_BODY);
1299 }
1300
1301 static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv,
1302                                int *unkc, const char **unkv)
1303 {
1304         const char *arg = argv[0];
1305         const char *optarg;
1306         int argcount;
1307
1308         /* pseudo revision arguments */
1309         if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") ||
1310             !strcmp(arg, "--tags") || !strcmp(arg, "--remotes") ||
1311             !strcmp(arg, "--reflog") || !strcmp(arg, "--not") ||
1312             !strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk") ||
1313             !strcmp(arg, "--bisect") || !prefixcmp(arg, "--glob=") ||
1314             !prefixcmp(arg, "--branches=") || !prefixcmp(arg, "--tags=") ||
1315             !prefixcmp(arg, "--remotes=") || !prefixcmp(arg, "--no-walk="))
1316         {
1317                 unkv[(*unkc)++] = arg;
1318                 return 1;
1319         }
1320
1321         if ((argcount = parse_long_opt("max-count", argv, &optarg))) {
1322                 revs->max_count = atoi(optarg);
1323                 revs->no_walk = 0;
1324                 return argcount;
1325         } else if ((argcount = parse_long_opt("skip", argv, &optarg))) {
1326                 revs->skip_count = atoi(optarg);
1327                 return argcount;
1328         } else if ((*arg == '-') && isdigit(arg[1])) {
1329         /* accept -<digit>, like traditional "head" */
1330                 revs->max_count = atoi(arg + 1);
1331                 revs->no_walk = 0;
1332         } else if (!strcmp(arg, "-n")) {
1333                 if (argc <= 1)
1334                         return error("-n requires an argument");
1335                 revs->max_count = atoi(argv[1]);
1336                 revs->no_walk = 0;
1337                 return 2;
1338         } else if (!prefixcmp(arg, "-n")) {
1339                 revs->max_count = atoi(arg + 2);
1340                 revs->no_walk = 0;
1341         } else if ((argcount = parse_long_opt("max-age", argv, &optarg))) {
1342                 revs->max_age = atoi(optarg);
1343                 return argcount;
1344         } else if ((argcount = parse_long_opt("since", argv, &optarg))) {
1345                 revs->max_age = approxidate(optarg);
1346                 return argcount;
1347         } else if ((argcount = parse_long_opt("after", argv, &optarg))) {
1348                 revs->max_age = approxidate(optarg);
1349                 return argcount;
1350         } else if ((argcount = parse_long_opt("min-age", argv, &optarg))) {
1351                 revs->min_age = atoi(optarg);
1352                 return argcount;
1353         } else if ((argcount = parse_long_opt("before", argv, &optarg))) {
1354                 revs->min_age = approxidate(optarg);
1355                 return argcount;
1356         } else if ((argcount = parse_long_opt("until", argv, &optarg))) {
1357                 revs->min_age = approxidate(optarg);
1358                 return argcount;
1359         } else if (!strcmp(arg, "--first-parent")) {
1360                 revs->first_parent_only = 1;
1361         } else if (!strcmp(arg, "--ancestry-path")) {
1362                 revs->ancestry_path = 1;
1363                 revs->simplify_history = 0;
1364                 revs->limited = 1;
1365         } else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) {
1366                 init_reflog_walk(&revs->reflog_info);
1367         } else if (!strcmp(arg, "--default")) {
1368                 if (argc <= 1)
1369                         return error("bad --default argument");
1370                 revs->def = argv[1];
1371                 return 2;
1372         } else if (!strcmp(arg, "--merge")) {
1373                 revs->show_merge = 1;
1374         } else if (!strcmp(arg, "--topo-order")) {
1375                 revs->lifo = 1;
1376                 revs->topo_order = 1;
1377         } else if (!strcmp(arg, "--simplify-merges")) {
1378                 revs->simplify_merges = 1;
1379                 revs->topo_order = 1;
1380                 revs->rewrite_parents = 1;
1381                 revs->simplify_history = 0;
1382                 revs->limited = 1;
1383         } else if (!strcmp(arg, "--simplify-by-decoration")) {
1384                 revs->simplify_merges = 1;
1385                 revs->topo_order = 1;
1386                 revs->rewrite_parents = 1;
1387                 revs->simplify_history = 0;
1388                 revs->simplify_by_decoration = 1;
1389                 revs->limited = 1;
1390                 revs->prune = 1;
1391                 load_ref_decorations(DECORATE_SHORT_REFS);
1392         } else if (!strcmp(arg, "--date-order")) {
1393                 revs->lifo = 0;
1394                 revs->topo_order = 1;
1395         } else if (!prefixcmp(arg, "--early-output")) {
1396                 int count = 100;
1397                 switch (arg[14]) {
1398                 case '=':
1399                         count = atoi(arg+15);
1400                         /* Fallthrough */
1401                 case 0:
1402                         revs->topo_order = 1;
1403                        revs->early_output = count;
1404                 }
1405         } else if (!strcmp(arg, "--parents")) {
1406                 revs->rewrite_parents = 1;
1407                 revs->print_parents = 1;
1408         } else if (!strcmp(arg, "--dense")) {
1409                 revs->dense = 1;
1410         } else if (!strcmp(arg, "--sparse")) {
1411                 revs->dense = 0;
1412         } else if (!strcmp(arg, "--show-all")) {
1413                 revs->show_all = 1;
1414         } else if (!strcmp(arg, "--remove-empty")) {
1415                 revs->remove_empty_trees = 1;
1416         } else if (!strcmp(arg, "--merges")) {
1417                 revs->min_parents = 2;
1418         } else if (!strcmp(arg, "--no-merges")) {
1419                 revs->max_parents = 1;
1420         } else if (!prefixcmp(arg, "--min-parents=")) {
1421                 revs->min_parents = atoi(arg+14);
1422         } else if (!prefixcmp(arg, "--no-min-parents")) {
1423                 revs->min_parents = 0;
1424         } else if (!prefixcmp(arg, "--max-parents=")) {
1425                 revs->max_parents = atoi(arg+14);
1426         } else if (!prefixcmp(arg, "--no-max-parents")) {
1427                 revs->max_parents = -1;
1428         } else if (!strcmp(arg, "--boundary")) {
1429                 revs->boundary = 1;
1430         } else if (!strcmp(arg, "--left-right")) {
1431                 revs->left_right = 1;
1432         } else if (!strcmp(arg, "--left-only")) {
1433                 if (revs->right_only)
1434                         die("--left-only is incompatible with --right-only"
1435                             " or --cherry");
1436                 revs->left_only = 1;
1437         } else if (!strcmp(arg, "--right-only")) {
1438                 if (revs->left_only)
1439                         die("--right-only is incompatible with --left-only");
1440                 revs->right_only = 1;
1441         } else if (!strcmp(arg, "--cherry")) {
1442                 if (revs->left_only)
1443                         die("--cherry is incompatible with --left-only");
1444                 revs->cherry_mark = 1;
1445                 revs->right_only = 1;
1446                 revs->max_parents = 1;
1447                 revs->limited = 1;
1448         } else if (!strcmp(arg, "--count")) {
1449                 revs->count = 1;
1450         } else if (!strcmp(arg, "--cherry-mark")) {
1451                 if (revs->cherry_pick)
1452                         die("--cherry-mark is incompatible with --cherry-pick");
1453                 revs->cherry_mark = 1;
1454                 revs->limited = 1; /* needs limit_list() */
1455         } else if (!strcmp(arg, "--cherry-pick")) {
1456                 if (revs->cherry_mark)
1457                         die("--cherry-pick is incompatible with --cherry-mark");
1458                 revs->cherry_pick = 1;
1459                 revs->limited = 1;
1460         } else if (!strcmp(arg, "--objects")) {
1461                 revs->tag_objects = 1;
1462                 revs->tree_objects = 1;
1463                 revs->blob_objects = 1;
1464         } else if (!strcmp(arg, "--objects-edge")) {
1465                 revs->tag_objects = 1;
1466                 revs->tree_objects = 1;
1467                 revs->blob_objects = 1;
1468                 revs->edge_hint = 1;
1469         } else if (!strcmp(arg, "--verify-objects")) {
1470                 revs->tag_objects = 1;
1471                 revs->tree_objects = 1;
1472                 revs->blob_objects = 1;
1473                 revs->verify_objects = 1;
1474         } else if (!strcmp(arg, "--unpacked")) {
1475                 revs->unpacked = 1;
1476         } else if (!prefixcmp(arg, "--unpacked=")) {
1477                 die("--unpacked=<packfile> no longer supported.");
1478         } else if (!strcmp(arg, "-r")) {
1479                 revs->diff = 1;
1480                 DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
1481         } else if (!strcmp(arg, "-t")) {
1482                 revs->diff = 1;
1483                 DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
1484                 DIFF_OPT_SET(&revs->diffopt, TREE_IN_RECURSIVE);
1485         } else if (!strcmp(arg, "-m")) {
1486                 revs->ignore_merges = 0;
1487         } else if (!strcmp(arg, "-c")) {
1488                 revs->diff = 1;
1489                 revs->dense_combined_merges = 0;
1490                 revs->combine_merges = 1;
1491         } else if (!strcmp(arg, "--cc")) {
1492                 revs->diff = 1;
1493                 revs->dense_combined_merges = 1;
1494                 revs->combine_merges = 1;
1495         } else if (!strcmp(arg, "-v")) {
1496                 revs->verbose_header = 1;
1497         } else if (!strcmp(arg, "--pretty")) {
1498                 revs->verbose_header = 1;
1499                 revs->pretty_given = 1;
1500                 get_commit_format(arg+8, revs);
1501         } else if (!prefixcmp(arg, "--pretty=") || !prefixcmp(arg, "--format=")) {
1502                 /*
1503                  * Detached form ("--pretty X" as opposed to "--pretty=X")
1504                  * not allowed, since the argument is optional.
1505                  */
1506                 revs->verbose_header = 1;
1507                 revs->pretty_given = 1;
1508                 get_commit_format(arg+9, revs);
1509         } else if (!strcmp(arg, "--show-notes") || !strcmp(arg, "--notes")) {
1510                 revs->show_notes = 1;
1511                 revs->show_notes_given = 1;
1512                 revs->notes_opt.use_default_notes = 1;
1513         } else if (!strcmp(arg, "--show-signature")) {
1514                 revs->show_signature = 1;
1515         } else if (!prefixcmp(arg, "--show-notes=") ||
1516                    !prefixcmp(arg, "--notes=")) {
1517                 struct strbuf buf = STRBUF_INIT;
1518                 revs->show_notes = 1;
1519                 revs->show_notes_given = 1;
1520                 if (!prefixcmp(arg, "--show-notes")) {
1521                         if (revs->notes_opt.use_default_notes < 0)
1522                                 revs->notes_opt.use_default_notes = 1;
1523                         strbuf_addstr(&buf, arg+13);
1524                 }
1525                 else
1526                         strbuf_addstr(&buf, arg+8);
1527                 expand_notes_ref(&buf);
1528                 string_list_append(&revs->notes_opt.extra_notes_refs,
1529                                    strbuf_detach(&buf, NULL));
1530         } else if (!strcmp(arg, "--no-notes")) {
1531                 revs->show_notes = 0;
1532                 revs->show_notes_given = 1;
1533                 revs->notes_opt.use_default_notes = -1;
1534                 /* we have been strdup'ing ourselves, so trick
1535                  * string_list into free()ing strings */
1536                 revs->notes_opt.extra_notes_refs.strdup_strings = 1;
1537                 string_list_clear(&revs->notes_opt.extra_notes_refs, 0);
1538                 revs->notes_opt.extra_notes_refs.strdup_strings = 0;
1539         } else if (!strcmp(arg, "--standard-notes")) {
1540                 revs->show_notes_given = 1;
1541                 revs->notes_opt.use_default_notes = 1;
1542         } else if (!strcmp(arg, "--no-standard-notes")) {
1543                 revs->notes_opt.use_default_notes = 0;
1544         } else if (!strcmp(arg, "--oneline")) {
1545                 revs->verbose_header = 1;
1546                 get_commit_format("oneline", revs);
1547                 revs->pretty_given = 1;
1548                 revs->abbrev_commit = 1;
1549         } else if (!strcmp(arg, "--graph")) {
1550                 revs->topo_order = 1;
1551                 revs->rewrite_parents = 1;
1552                 revs->graph = graph_init(revs);
1553         } else if (!strcmp(arg, "--root")) {
1554                 revs->show_root_diff = 1;
1555         } else if (!strcmp(arg, "--no-commit-id")) {
1556                 revs->no_commit_id = 1;
1557         } else if (!strcmp(arg, "--always")) {
1558                 revs->always_show_header = 1;
1559         } else if (!strcmp(arg, "--no-abbrev")) {
1560                 revs->abbrev = 0;
1561         } else if (!strcmp(arg, "--abbrev")) {
1562                 revs->abbrev = DEFAULT_ABBREV;
1563         } else if (!prefixcmp(arg, "--abbrev=")) {
1564                 revs->abbrev = strtoul(arg + 9, NULL, 10);
1565                 if (revs->abbrev < MINIMUM_ABBREV)
1566                         revs->abbrev = MINIMUM_ABBREV;
1567                 else if (revs->abbrev > 40)
1568                         revs->abbrev = 40;
1569         } else if (!strcmp(arg, "--abbrev-commit")) {
1570                 revs->abbrev_commit = 1;
1571                 revs->abbrev_commit_given = 1;
1572         } else if (!strcmp(arg, "--no-abbrev-commit")) {
1573                 revs->abbrev_commit = 0;
1574         } else if (!strcmp(arg, "--full-diff")) {
1575                 revs->diff = 1;
1576                 revs->full_diff = 1;
1577         } else if (!strcmp(arg, "--full-history")) {
1578                 revs->simplify_history = 0;
1579         } else if (!strcmp(arg, "--relative-date")) {
1580                 revs->date_mode = DATE_RELATIVE;
1581                 revs->date_mode_explicit = 1;
1582         } else if ((argcount = parse_long_opt("date", argv, &optarg))) {
1583                 revs->date_mode = parse_date_format(optarg);
1584                 revs->date_mode_explicit = 1;
1585                 return argcount;
1586         } else if (!strcmp(arg, "--log-size")) {
1587                 revs->show_log_size = 1;
1588         }
1589         /*
1590          * Grepping the commit log
1591          */
1592         else if ((argcount = parse_long_opt("author", argv, &optarg))) {
1593                 add_header_grep(revs, GREP_HEADER_AUTHOR, optarg);
1594                 return argcount;
1595         } else if ((argcount = parse_long_opt("committer", argv, &optarg))) {
1596                 add_header_grep(revs, GREP_HEADER_COMMITTER, optarg);
1597                 return argcount;
1598         } else if ((argcount = parse_long_opt("grep-reflog", argv, &optarg))) {
1599                 add_header_grep(revs, GREP_HEADER_REFLOG, optarg);
1600                 return argcount;
1601         } else if ((argcount = parse_long_opt("grep", argv, &optarg))) {
1602                 add_message_grep(revs, optarg);
1603                 return argcount;
1604         } else if (!strcmp(arg, "--grep-debug")) {
1605                 revs->grep_filter.debug = 1;
1606         } else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) {
1607                 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, &revs->grep_filter);
1608         } else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) {
1609                 revs->grep_filter.regflags |= REG_ICASE;
1610                 DIFF_OPT_SET(&revs->diffopt, PICKAXE_IGNORE_CASE);
1611         } else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) {
1612                 grep_set_pattern_type_option(GREP_PATTERN_TYPE_FIXED, &revs->grep_filter);
1613         } else if (!strcmp(arg, "--all-match")) {
1614                 revs->grep_filter.all_match = 1;
1615         } else if ((argcount = parse_long_opt("encoding", argv, &optarg))) {
1616                 if (strcmp(optarg, "none"))
1617                         git_log_output_encoding = xstrdup(optarg);
1618                 else
1619                         git_log_output_encoding = "";
1620                 return argcount;
1621         } else if (!strcmp(arg, "--reverse")) {
1622                 revs->reverse ^= 1;
1623         } else if (!strcmp(arg, "--children")) {
1624                 revs->children.name = "children";
1625                 revs->limited = 1;
1626         } else if (!strcmp(arg, "--ignore-missing")) {
1627                 revs->ignore_missing = 1;
1628         } else {
1629                 int opts = diff_opt_parse(&revs->diffopt, argv, argc);
1630                 if (!opts)
1631                         unkv[(*unkc)++] = arg;
1632                 return opts;
1633         }
1634
1635         return 1;
1636 }
1637
1638 void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx,
1639                         const struct option *options,
1640                         const char * const usagestr[])
1641 {
1642         int n = handle_revision_opt(revs, ctx->argc, ctx->argv,
1643                                     &ctx->cpidx, ctx->out);
1644         if (n <= 0) {
1645                 error("unknown option `%s'", ctx->argv[0]);
1646                 usage_with_options(usagestr, options);
1647         }
1648         ctx->argv += n;
1649         ctx->argc -= n;
1650 }
1651
1652 static int for_each_bad_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1653 {
1654         return for_each_ref_in_submodule(submodule, "refs/bisect/bad", fn, cb_data);
1655 }
1656
1657 static int for_each_good_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1658 {
1659         return for_each_ref_in_submodule(submodule, "refs/bisect/good", fn, cb_data);
1660 }
1661
1662 static int handle_revision_pseudo_opt(const char *submodule,
1663                                 struct rev_info *revs,
1664                                 int argc, const char **argv, int *flags)
1665 {
1666         const char *arg = argv[0];
1667         const char *optarg;
1668         int argcount;
1669
1670         /*
1671          * NOTE!
1672          *
1673          * Commands like "git shortlog" will not accept the options below
1674          * unless parse_revision_opt queues them (as opposed to erroring
1675          * out).
1676          *
1677          * When implementing your new pseudo-option, remember to
1678          * register it in the list at the top of handle_revision_opt.
1679          */
1680         if (!strcmp(arg, "--all")) {
1681                 handle_refs(submodule, revs, *flags, for_each_ref_submodule);
1682                 handle_refs(submodule, revs, *flags, head_ref_submodule);
1683         } else if (!strcmp(arg, "--branches")) {
1684                 handle_refs(submodule, revs, *flags, for_each_branch_ref_submodule);
1685         } else if (!strcmp(arg, "--bisect")) {
1686                 handle_refs(submodule, revs, *flags, for_each_bad_bisect_ref);
1687                 handle_refs(submodule, revs, *flags ^ UNINTERESTING, for_each_good_bisect_ref);
1688                 revs->bisect = 1;
1689         } else if (!strcmp(arg, "--tags")) {
1690                 handle_refs(submodule, revs, *flags, for_each_tag_ref_submodule);
1691         } else if (!strcmp(arg, "--remotes")) {
1692                 handle_refs(submodule, revs, *flags, for_each_remote_ref_submodule);
1693         } else if ((argcount = parse_long_opt("glob", argv, &optarg))) {
1694                 struct all_refs_cb cb;
1695                 init_all_refs_cb(&cb, revs, *flags);
1696                 for_each_glob_ref(handle_one_ref, optarg, &cb);
1697                 return argcount;
1698         } else if (!prefixcmp(arg, "--branches=")) {
1699                 struct all_refs_cb cb;
1700                 init_all_refs_cb(&cb, revs, *flags);
1701                 for_each_glob_ref_in(handle_one_ref, arg + 11, "refs/heads/", &cb);
1702         } else if (!prefixcmp(arg, "--tags=")) {
1703                 struct all_refs_cb cb;
1704                 init_all_refs_cb(&cb, revs, *flags);
1705                 for_each_glob_ref_in(handle_one_ref, arg + 7, "refs/tags/", &cb);
1706         } else if (!prefixcmp(arg, "--remotes=")) {
1707                 struct all_refs_cb cb;
1708                 init_all_refs_cb(&cb, revs, *flags);
1709                 for_each_glob_ref_in(handle_one_ref, arg + 10, "refs/remotes/", &cb);
1710         } else if (!strcmp(arg, "--reflog")) {
1711                 handle_reflog(revs, *flags);
1712         } else if (!strcmp(arg, "--not")) {
1713                 *flags ^= UNINTERESTING;
1714         } else if (!strcmp(arg, "--no-walk")) {
1715                 revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
1716         } else if (!prefixcmp(arg, "--no-walk=")) {
1717                 /*
1718                  * Detached form ("--no-walk X" as opposed to "--no-walk=X")
1719                  * not allowed, since the argument is optional.
1720                  */
1721                 if (!strcmp(arg + 10, "sorted"))
1722                         revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
1723                 else if (!strcmp(arg + 10, "unsorted"))
1724                         revs->no_walk = REVISION_WALK_NO_WALK_UNSORTED;
1725                 else
1726                         return error("invalid argument to --no-walk");
1727         } else if (!strcmp(arg, "--do-walk")) {
1728                 revs->no_walk = 0;
1729         } else {
1730                 return 0;
1731         }
1732
1733         return 1;
1734 }
1735
1736 /*
1737  * Parse revision information, filling in the "rev_info" structure,
1738  * and removing the used arguments from the argument list.
1739  *
1740  * Returns the number of arguments left that weren't recognized
1741  * (which are also moved to the head of the argument list)
1742  */
1743 int setup_revisions(int argc, const char **argv, struct rev_info *revs, struct setup_revision_opt *opt)
1744 {
1745         int i, flags, left, seen_dashdash, read_from_stdin, got_rev_arg = 0, revarg_opt;
1746         struct cmdline_pathspec prune_data;
1747         const char *submodule = NULL;
1748
1749         memset(&prune_data, 0, sizeof(prune_data));
1750         if (opt)
1751                 submodule = opt->submodule;
1752
1753         /* First, search for "--" */
1754         if (opt && opt->assume_dashdash) {
1755                 seen_dashdash = 1;
1756         } else {
1757                 seen_dashdash = 0;
1758                 for (i = 1; i < argc; i++) {
1759                         const char *arg = argv[i];
1760                         if (strcmp(arg, "--"))
1761                                 continue;
1762                         argv[i] = NULL;
1763                         argc = i;
1764                         if (argv[i + 1])
1765                                 append_prune_data(&prune_data, argv + i + 1);
1766                         seen_dashdash = 1;
1767                         break;
1768                 }
1769         }
1770
1771         /* Second, deal with arguments and options */
1772         flags = 0;
1773         revarg_opt = opt ? opt->revarg_opt : 0;
1774         if (seen_dashdash)
1775                 revarg_opt |= REVARG_CANNOT_BE_FILENAME;
1776         read_from_stdin = 0;
1777         for (left = i = 1; i < argc; i++) {
1778                 const char *arg = argv[i];
1779                 if (*arg == '-') {
1780                         int opts;
1781
1782                         opts = handle_revision_pseudo_opt(submodule,
1783                                                 revs, argc - i, argv + i,
1784                                                 &flags);
1785                         if (opts > 0) {
1786                                 i += opts - 1;
1787                                 continue;
1788                         }
1789
1790                         if (!strcmp(arg, "--stdin")) {
1791                                 if (revs->disable_stdin) {
1792                                         argv[left++] = arg;
1793                                         continue;
1794                                 }
1795                                 if (read_from_stdin++)
1796                                         die("--stdin given twice?");
1797                                 read_revisions_from_stdin(revs, &prune_data);
1798                                 continue;
1799                         }
1800
1801                         opts = handle_revision_opt(revs, argc - i, argv + i, &left, argv);
1802                         if (opts > 0) {
1803                                 i += opts - 1;
1804                                 continue;
1805                         }
1806                         if (opts < 0)
1807                                 exit(128);
1808                         continue;
1809                 }
1810
1811
1812                 if (handle_revision_arg(arg, revs, flags, revarg_opt)) {
1813                         int j;
1814                         if (seen_dashdash || *arg == '^')
1815                                 die("bad revision '%s'", arg);
1816
1817                         /* If we didn't have a "--":
1818                          * (1) all filenames must exist;
1819                          * (2) all rev-args must not be interpretable
1820                          *     as a valid filename.
1821                          * but the latter we have checked in the main loop.
1822                          */
1823                         for (j = i; j < argc; j++)
1824                                 verify_filename(revs->prefix, argv[j], j == i);
1825
1826                         append_prune_data(&prune_data, argv + i);
1827                         break;
1828                 }
1829                 else
1830                         got_rev_arg = 1;
1831         }
1832
1833         if (prune_data.nr) {
1834                 /*
1835                  * If we need to introduce the magic "a lone ':' means no
1836                  * pathspec whatsoever", here is the place to do so.
1837                  *
1838                  * if (prune_data.nr == 1 && !strcmp(prune_data[0], ":")) {
1839                  *      prune_data.nr = 0;
1840                  *      prune_data.alloc = 0;
1841                  *      free(prune_data.path);
1842                  *      prune_data.path = NULL;
1843                  * } else {
1844                  *      terminate prune_data.alloc with NULL and
1845                  *      call init_pathspec() to set revs->prune_data here.
1846                  * }
1847                  */
1848                 ALLOC_GROW(prune_data.path, prune_data.nr+1, prune_data.alloc);
1849                 prune_data.path[prune_data.nr++] = NULL;
1850                 init_pathspec(&revs->prune_data,
1851                               get_pathspec(revs->prefix, prune_data.path));
1852         }
1853
1854         if (revs->def == NULL)
1855                 revs->def = opt ? opt->def : NULL;
1856         if (opt && opt->tweak)
1857                 opt->tweak(revs, opt);
1858         if (revs->show_merge)
1859                 prepare_show_merge(revs);
1860         if (revs->def && !revs->pending.nr && !got_rev_arg) {
1861                 unsigned char sha1[20];
1862                 struct object *object;
1863                 struct object_context oc;
1864                 if (get_sha1_with_context(revs->def, 0, sha1, &oc))
1865                         die("bad default revision '%s'", revs->def);
1866                 object = get_reference(revs, revs->def, sha1, 0);
1867                 add_pending_object_with_mode(revs, object, revs->def, oc.mode);
1868         }
1869
1870         /* Did the user ask for any diff output? Run the diff! */
1871         if (revs->diffopt.output_format & ~DIFF_FORMAT_NO_OUTPUT)
1872                 revs->diff = 1;
1873
1874         /* Pickaxe, diff-filter and rename following need diffs */
1875         if (revs->diffopt.pickaxe ||
1876             revs->diffopt.filter ||
1877             DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
1878                 revs->diff = 1;
1879
1880         if (revs->topo_order)
1881                 revs->limited = 1;
1882
1883         if (revs->prune_data.nr) {
1884                 diff_tree_setup_paths(revs->prune_data.raw, &revs->pruning);
1885                 /* Can't prune commits with rename following: the paths change.. */
1886                 if (!DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
1887                         revs->prune = 1;
1888                 if (!revs->full_diff)
1889                         diff_tree_setup_paths(revs->prune_data.raw, &revs->diffopt);
1890         }
1891         if (revs->combine_merges)
1892                 revs->ignore_merges = 0;
1893         revs->diffopt.abbrev = revs->abbrev;
1894         diff_setup_done(&revs->diffopt);
1895
1896         grep_commit_pattern_type(GREP_PATTERN_TYPE_UNSPECIFIED,
1897                                  &revs->grep_filter);
1898         compile_grep_patterns(&revs->grep_filter);
1899
1900         if (revs->reverse && revs->reflog_info)
1901                 die("cannot combine --reverse with --walk-reflogs");
1902         if (revs->rewrite_parents && revs->children.name)
1903                 die("cannot combine --parents and --children");
1904
1905         /*
1906          * Limitations on the graph functionality
1907          */
1908         if (revs->reverse && revs->graph)
1909                 die("cannot combine --reverse with --graph");
1910
1911         if (revs->reflog_info && revs->graph)
1912                 die("cannot combine --walk-reflogs with --graph");
1913         if (!revs->reflog_info && revs->grep_filter.use_reflog_filter)
1914                 die("cannot use --grep-reflog without --walk-reflogs");
1915
1916         return left;
1917 }
1918
1919 static void add_child(struct rev_info *revs, struct commit *parent, struct commit *child)
1920 {
1921         struct commit_list *l = xcalloc(1, sizeof(*l));
1922
1923         l->item = child;
1924         l->next = add_decoration(&revs->children, &parent->object, l);
1925 }
1926
1927 static int remove_duplicate_parents(struct commit *commit)
1928 {
1929         struct commit_list **pp, *p;
1930         int surviving_parents;
1931
1932         /* Examine existing parents while marking ones we have seen... */
1933         pp = &commit->parents;
1934         while ((p = *pp) != NULL) {
1935                 struct commit *parent = p->item;
1936                 if (parent->object.flags & TMP_MARK) {
1937                         *pp = p->next;
1938                         continue;
1939                 }
1940                 parent->object.flags |= TMP_MARK;
1941                 pp = &p->next;
1942         }
1943         /* count them while clearing the temporary mark */
1944         surviving_parents = 0;
1945         for (p = commit->parents; p; p = p->next) {
1946                 p->item->object.flags &= ~TMP_MARK;
1947                 surviving_parents++;
1948         }
1949         return surviving_parents;
1950 }
1951
1952 struct merge_simplify_state {
1953         struct commit *simplified;
1954 };
1955
1956 static struct merge_simplify_state *locate_simplify_state(struct rev_info *revs, struct commit *commit)
1957 {
1958         struct merge_simplify_state *st;
1959
1960         st = lookup_decoration(&revs->merge_simplification, &commit->object);
1961         if (!st) {
1962                 st = xcalloc(1, sizeof(*st));
1963                 add_decoration(&revs->merge_simplification, &commit->object, st);
1964         }
1965         return st;
1966 }
1967
1968 static struct commit_list **simplify_one(struct rev_info *revs, struct commit *commit, struct commit_list **tail)
1969 {
1970         struct commit_list *p;
1971         struct merge_simplify_state *st, *pst;
1972         int cnt;
1973
1974         st = locate_simplify_state(revs, commit);
1975
1976         /*
1977          * Have we handled this one?
1978          */
1979         if (st->simplified)
1980                 return tail;
1981
1982         /*
1983          * An UNINTERESTING commit simplifies to itself, so does a
1984          * root commit.  We do not rewrite parents of such commit
1985          * anyway.
1986          */
1987         if ((commit->object.flags & UNINTERESTING) || !commit->parents) {
1988                 st->simplified = commit;
1989                 return tail;
1990         }
1991
1992         /*
1993          * Do we know what commit all of our parents that matter
1994          * should be rewritten to?  Otherwise we are not ready to
1995          * rewrite this one yet.
1996          */
1997         for (cnt = 0, p = commit->parents; p; p = p->next) {
1998                 pst = locate_simplify_state(revs, p->item);
1999                 if (!pst->simplified) {
2000                         tail = &commit_list_insert(p->item, tail)->next;
2001                         cnt++;
2002                 }
2003                 if (revs->first_parent_only)
2004                         break;
2005         }
2006         if (cnt) {
2007                 tail = &commit_list_insert(commit, tail)->next;
2008                 return tail;
2009         }
2010
2011         /*
2012          * Rewrite our list of parents.
2013          */
2014         for (p = commit->parents; p; p = p->next) {
2015                 pst = locate_simplify_state(revs, p->item);
2016                 p->item = pst->simplified;
2017                 if (revs->first_parent_only)
2018                         break;
2019         }
2020         if (!revs->first_parent_only)
2021                 cnt = remove_duplicate_parents(commit);
2022         else
2023                 cnt = 1;
2024
2025         /*
2026          * It is possible that we are a merge and one side branch
2027          * does not have any commit that touches the given paths;
2028          * in such a case, the immediate parents will be rewritten
2029          * to different commits.
2030          *
2031          *      o----X          X: the commit we are looking at;
2032          *     /    /           o: a commit that touches the paths;
2033          * ---o----'
2034          *
2035          * Further reduce the parents by removing redundant parents.
2036          */
2037         if (1 < cnt) {
2038                 struct commit_list *h = reduce_heads(commit->parents);
2039                 cnt = commit_list_count(h);
2040                 free_commit_list(commit->parents);
2041                 commit->parents = h;
2042         }
2043
2044         /*
2045          * A commit simplifies to itself if it is a root, if it is
2046          * UNINTERESTING, if it touches the given paths, or if it is a
2047          * merge and its parents simplifies to more than one commits
2048          * (the first two cases are already handled at the beginning of
2049          * this function).
2050          *
2051          * Otherwise, it simplifies to what its sole parent simplifies to.
2052          */
2053         if (!cnt ||
2054             (commit->object.flags & UNINTERESTING) ||
2055             !(commit->object.flags & TREESAME) ||
2056             (1 < cnt))
2057                 st->simplified = commit;
2058         else {
2059                 pst = locate_simplify_state(revs, commit->parents->item);
2060                 st->simplified = pst->simplified;
2061         }
2062         return tail;
2063 }
2064
2065 static void simplify_merges(struct rev_info *revs)
2066 {
2067         struct commit_list *list, *next;
2068         struct commit_list *yet_to_do, **tail;
2069         struct commit *commit;
2070
2071         if (!revs->prune)
2072                 return;
2073
2074         /* feed the list reversed */
2075         yet_to_do = NULL;
2076         for (list = revs->commits; list; list = next) {
2077                 commit = list->item;
2078                 next = list->next;
2079                 /*
2080                  * Do not free(list) here yet; the original list
2081                  * is used later in this function.
2082                  */
2083                 commit_list_insert(commit, &yet_to_do);
2084         }
2085         while (yet_to_do) {
2086                 list = yet_to_do;
2087                 yet_to_do = NULL;
2088                 tail = &yet_to_do;
2089                 while (list) {
2090                         commit = list->item;
2091                         next = list->next;
2092                         free(list);
2093                         list = next;
2094                         tail = simplify_one(revs, commit, tail);
2095                 }
2096         }
2097
2098         /* clean up the result, removing the simplified ones */
2099         list = revs->commits;
2100         revs->commits = NULL;
2101         tail = &revs->commits;
2102         while (list) {
2103                 struct merge_simplify_state *st;
2104
2105                 commit = list->item;
2106                 next = list->next;
2107                 free(list);
2108                 list = next;
2109                 st = locate_simplify_state(revs, commit);
2110                 if (st->simplified == commit)
2111                         tail = &commit_list_insert(commit, tail)->next;
2112         }
2113 }
2114
2115 static void set_children(struct rev_info *revs)
2116 {
2117         struct commit_list *l;
2118         for (l = revs->commits; l; l = l->next) {
2119                 struct commit *commit = l->item;
2120                 struct commit_list *p;
2121
2122                 for (p = commit->parents; p; p = p->next)
2123                         add_child(revs, p->item, commit);
2124         }
2125 }
2126
2127 void reset_revision_walk(void)
2128 {
2129         clear_object_flags(SEEN | ADDED | SHOWN);
2130 }
2131
2132 int prepare_revision_walk(struct rev_info *revs)
2133 {
2134         int nr = revs->pending.nr;
2135         struct object_array_entry *e, *list;
2136         struct commit_list **next = &revs->commits;
2137
2138         e = list = revs->pending.objects;
2139         revs->pending.nr = 0;
2140         revs->pending.alloc = 0;
2141         revs->pending.objects = NULL;
2142         while (--nr >= 0) {
2143                 struct commit *commit = handle_commit(revs, e->item, e->name);
2144                 if (commit) {
2145                         if (!(commit->object.flags & SEEN)) {
2146                                 commit->object.flags |= SEEN;
2147                                 next = commit_list_append(commit, next);
2148                         }
2149                 }
2150                 e++;
2151         }
2152         if (!revs->leak_pending)
2153                 free(list);
2154
2155         if (revs->no_walk != REVISION_WALK_NO_WALK_UNSORTED)
2156                 commit_list_sort_by_date(&revs->commits);
2157         if (revs->no_walk)
2158                 return 0;
2159         if (revs->limited)
2160                 if (limit_list(revs) < 0)
2161                         return -1;
2162         if (revs->topo_order)
2163                 sort_in_topological_order(&revs->commits, revs->lifo);
2164         if (revs->simplify_merges)
2165                 simplify_merges(revs);
2166         if (revs->children.name)
2167                 set_children(revs);
2168         return 0;
2169 }
2170
2171 enum rewrite_result {
2172         rewrite_one_ok,
2173         rewrite_one_noparents,
2174         rewrite_one_error
2175 };
2176
2177 static enum rewrite_result rewrite_one(struct rev_info *revs, struct commit **pp)
2178 {
2179         struct commit_list *cache = NULL;
2180
2181         for (;;) {
2182                 struct commit *p = *pp;
2183                 if (!revs->limited)
2184                         if (add_parents_to_list(revs, p, &revs->commits, &cache) < 0)
2185                                 return rewrite_one_error;
2186                 if (p->parents && p->parents->next)
2187                         return rewrite_one_ok;
2188                 if (p->object.flags & UNINTERESTING)
2189                         return rewrite_one_ok;
2190                 if (!(p->object.flags & TREESAME))
2191                         return rewrite_one_ok;
2192                 if (!p->parents)
2193                         return rewrite_one_noparents;
2194                 *pp = p->parents->item;
2195         }
2196 }
2197
2198 static int rewrite_parents(struct rev_info *revs, struct commit *commit)
2199 {
2200         struct commit_list **pp = &commit->parents;
2201         while (*pp) {
2202                 struct commit_list *parent = *pp;
2203                 switch (rewrite_one(revs, &parent->item)) {
2204                 case rewrite_one_ok:
2205                         break;
2206                 case rewrite_one_noparents:
2207                         *pp = parent->next;
2208                         continue;
2209                 case rewrite_one_error:
2210                         return -1;
2211                 }
2212                 pp = &parent->next;
2213         }
2214         remove_duplicate_parents(commit);
2215         return 0;
2216 }
2217
2218 static int commit_match(struct commit *commit, struct rev_info *opt)
2219 {
2220         int retval;
2221         struct strbuf buf = STRBUF_INIT;
2222         if (!opt->grep_filter.pattern_list && !opt->grep_filter.header_list)
2223                 return 1;
2224
2225         /* Prepend "fake" headers as needed */
2226         if (opt->grep_filter.use_reflog_filter) {
2227                 strbuf_addstr(&buf, "reflog ");
2228                 get_reflog_message(&buf, opt->reflog_info);
2229                 strbuf_addch(&buf, '\n');
2230         }
2231
2232         /* Copy the commit to temporary if we are using "fake" headers */
2233         if (buf.len)
2234                 strbuf_addstr(&buf, commit->buffer);
2235
2236         /* Append "fake" message parts as needed */
2237         if (opt->show_notes) {
2238                 if (!buf.len)
2239                         strbuf_addstr(&buf, commit->buffer);
2240                 format_display_notes(commit->object.sha1, &buf,
2241                                      get_log_output_encoding(), 0);
2242         }
2243
2244         /* Find either in the commit object, or in the temporary */
2245         if (buf.len)
2246                 retval = grep_buffer(&opt->grep_filter, buf.buf, buf.len);
2247         else
2248                 retval = grep_buffer(&opt->grep_filter,
2249                                      commit->buffer, strlen(commit->buffer));
2250         strbuf_release(&buf);
2251         return retval;
2252 }
2253
2254 static inline int want_ancestry(struct rev_info *revs)
2255 {
2256         return (revs->rewrite_parents || revs->children.name);
2257 }
2258
2259 enum commit_action get_commit_action(struct rev_info *revs, struct commit *commit)
2260 {
2261         if (commit->object.flags & SHOWN)
2262                 return commit_ignore;
2263         if (revs->unpacked && has_sha1_pack(commit->object.sha1))
2264                 return commit_ignore;
2265         if (revs->show_all)
2266                 return commit_show;
2267         if (commit->object.flags & UNINTERESTING)
2268                 return commit_ignore;
2269         if (revs->min_age != -1 && (commit->date > revs->min_age))
2270                 return commit_ignore;
2271         if (revs->min_parents || (revs->max_parents >= 0)) {
2272                 int n = 0;
2273                 struct commit_list *p;
2274                 for (p = commit->parents; p; p = p->next)
2275                         n++;
2276                 if ((n < revs->min_parents) ||
2277                     ((revs->max_parents >= 0) && (n > revs->max_parents)))
2278                         return commit_ignore;
2279         }
2280         if (!commit_match(commit, revs))
2281                 return commit_ignore;
2282         if (revs->prune && revs->dense) {
2283                 /* Commit without changes? */
2284                 if (commit->object.flags & TREESAME) {
2285                         /* drop merges unless we want parenthood */
2286                         if (!want_ancestry(revs))
2287                                 return commit_ignore;
2288                         /* non-merge - always ignore it */
2289                         if (!commit->parents || !commit->parents->next)
2290                                 return commit_ignore;
2291                 }
2292         }
2293         return commit_show;
2294 }
2295
2296 enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit)
2297 {
2298         enum commit_action action = get_commit_action(revs, commit);
2299
2300         if (action == commit_show &&
2301             !revs->show_all &&
2302             revs->prune && revs->dense && want_ancestry(revs)) {
2303                 if (rewrite_parents(revs, commit) < 0)
2304                         return commit_error;
2305         }
2306         return action;
2307 }
2308
2309 static struct commit *get_revision_1(struct rev_info *revs)
2310 {
2311         if (!revs->commits)
2312                 return NULL;
2313
2314         do {
2315                 struct commit_list *entry = revs->commits;
2316                 struct commit *commit = entry->item;
2317
2318                 revs->commits = entry->next;
2319                 free(entry);
2320
2321                 if (revs->reflog_info) {
2322                         fake_reflog_parent(revs->reflog_info, commit);
2323                         commit->object.flags &= ~(ADDED | SEEN | SHOWN);
2324                 }
2325
2326                 /*
2327                  * If we haven't done the list limiting, we need to look at
2328                  * the parents here. We also need to do the date-based limiting
2329                  * that we'd otherwise have done in limit_list().
2330                  */
2331                 if (!revs->limited) {
2332                         if (revs->max_age != -1 &&
2333                             (commit->date < revs->max_age))
2334                                 continue;
2335                         if (add_parents_to_list(revs, commit, &revs->commits, NULL) < 0)
2336                                 die("Failed to traverse parents of commit %s",
2337                                     sha1_to_hex(commit->object.sha1));
2338                 }
2339
2340                 switch (simplify_commit(revs, commit)) {
2341                 case commit_ignore:
2342                         continue;
2343                 case commit_error:
2344                         die("Failed to simplify parents of commit %s",
2345                             sha1_to_hex(commit->object.sha1));
2346                 default:
2347                         return commit;
2348                 }
2349         } while (revs->commits);
2350         return NULL;
2351 }
2352
2353 static void gc_boundary(struct object_array *array)
2354 {
2355         unsigned nr = array->nr;
2356         unsigned alloc = array->alloc;
2357         struct object_array_entry *objects = array->objects;
2358
2359         if (alloc <= nr) {
2360                 unsigned i, j;
2361                 for (i = j = 0; i < nr; i++) {
2362                         if (objects[i].item->flags & SHOWN)
2363                                 continue;
2364                         if (i != j)
2365                                 objects[j] = objects[i];
2366                         j++;
2367                 }
2368                 for (i = j; i < nr; i++)
2369                         objects[i].item = NULL;
2370                 array->nr = j;
2371         }
2372 }
2373
2374 static void create_boundary_commit_list(struct rev_info *revs)
2375 {
2376         unsigned i;
2377         struct commit *c;
2378         struct object_array *array = &revs->boundary_commits;
2379         struct object_array_entry *objects = array->objects;
2380
2381         /*
2382          * If revs->commits is non-NULL at this point, an error occurred in
2383          * get_revision_1().  Ignore the error and continue printing the
2384          * boundary commits anyway.  (This is what the code has always
2385          * done.)
2386          */
2387         if (revs->commits) {
2388                 free_commit_list(revs->commits);
2389                 revs->commits = NULL;
2390         }
2391
2392         /*
2393          * Put all of the actual boundary commits from revs->boundary_commits
2394          * into revs->commits
2395          */
2396         for (i = 0; i < array->nr; i++) {
2397                 c = (struct commit *)(objects[i].item);
2398                 if (!c)
2399                         continue;
2400                 if (!(c->object.flags & CHILD_SHOWN))
2401                         continue;
2402                 if (c->object.flags & (SHOWN | BOUNDARY))
2403                         continue;
2404                 c->object.flags |= BOUNDARY;
2405                 commit_list_insert(c, &revs->commits);
2406         }
2407
2408         /*
2409          * If revs->topo_order is set, sort the boundary commits
2410          * in topological order
2411          */
2412         sort_in_topological_order(&revs->commits, revs->lifo);
2413 }
2414
2415 static struct commit *get_revision_internal(struct rev_info *revs)
2416 {
2417         struct commit *c = NULL;
2418         struct commit_list *l;
2419
2420         if (revs->boundary == 2) {
2421                 /*
2422                  * All of the normal commits have already been returned,
2423                  * and we are now returning boundary commits.
2424                  * create_boundary_commit_list() has populated
2425                  * revs->commits with the remaining commits to return.
2426                  */
2427                 c = pop_commit(&revs->commits);
2428                 if (c)
2429                         c->object.flags |= SHOWN;
2430                 return c;
2431         }
2432
2433         /*
2434          * If our max_count counter has reached zero, then we are done. We
2435          * don't simply return NULL because we still might need to show
2436          * boundary commits. But we want to avoid calling get_revision_1, which
2437          * might do a considerable amount of work finding the next commit only
2438          * for us to throw it away.
2439          *
2440          * If it is non-zero, then either we don't have a max_count at all
2441          * (-1), or it is still counting, in which case we decrement.
2442          */
2443         if (revs->max_count) {
2444                 c = get_revision_1(revs);
2445                 if (c) {
2446                         while (0 < revs->skip_count) {
2447                                 revs->skip_count--;
2448                                 c = get_revision_1(revs);
2449                                 if (!c)
2450                                         break;
2451                         }
2452                 }
2453
2454                 if (revs->max_count > 0)
2455                         revs->max_count--;
2456         }
2457
2458         if (c)
2459                 c->object.flags |= SHOWN;
2460
2461         if (!revs->boundary) {
2462                 return c;
2463         }
2464
2465         if (!c) {
2466                 /*
2467                  * get_revision_1() runs out the commits, and
2468                  * we are done computing the boundaries.
2469                  * switch to boundary commits output mode.
2470                  */
2471                 revs->boundary = 2;
2472
2473                 /*
2474                  * Update revs->commits to contain the list of
2475                  * boundary commits.
2476                  */
2477                 create_boundary_commit_list(revs);
2478
2479                 return get_revision_internal(revs);
2480         }
2481
2482         /*
2483          * boundary commits are the commits that are parents of the
2484          * ones we got from get_revision_1() but they themselves are
2485          * not returned from get_revision_1().  Before returning
2486          * 'c', we need to mark its parents that they could be boundaries.
2487          */
2488
2489         for (l = c->parents; l; l = l->next) {
2490                 struct object *p;
2491                 p = &(l->item->object);
2492                 if (p->flags & (CHILD_SHOWN | SHOWN))
2493                         continue;
2494                 p->flags |= CHILD_SHOWN;
2495                 gc_boundary(&revs->boundary_commits);
2496                 add_object_array(p, NULL, &revs->boundary_commits);
2497         }
2498
2499         return c;
2500 }
2501
2502 struct commit *get_revision(struct rev_info *revs)
2503 {
2504         struct commit *c;
2505         struct commit_list *reversed;
2506
2507         if (revs->reverse) {
2508                 reversed = NULL;
2509                 while ((c = get_revision_internal(revs))) {
2510                         commit_list_insert(c, &reversed);
2511                 }
2512                 revs->commits = reversed;
2513                 revs->reverse = 0;
2514                 revs->reverse_output_stage = 1;
2515         }
2516
2517         if (revs->reverse_output_stage)
2518                 return pop_commit(&revs->commits);
2519
2520         c = get_revision_internal(revs);
2521         if (c && revs->graph)
2522                 graph_update(revs->graph, c);
2523         return c;
2524 }
2525
2526 char *get_revision_mark(const struct rev_info *revs, const struct commit *commit)
2527 {
2528         if (commit->object.flags & BOUNDARY)
2529                 return "-";
2530         else if (commit->object.flags & UNINTERESTING)
2531                 return "^";
2532         else if (commit->object.flags & PATCHSAME)
2533                 return "=";
2534         else if (!revs || revs->left_right) {
2535                 if (commit->object.flags & SYMMETRIC_LEFT)
2536                         return "<";
2537                 else
2538                         return ">";
2539         } else if (revs->graph)
2540                 return "*";
2541         else if (revs->cherry_mark)
2542                 return "+";
2543         return "";
2544 }
2545
2546 void put_revision_mark(const struct rev_info *revs, const struct commit *commit)
2547 {
2548         char *mark = get_revision_mark(revs, commit);
2549         if (!strlen(mark))
2550                 return;
2551         fputs(mark, stdout);
2552         putchar(' ');
2553 }