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