git-update-index.txt: Document the --really-refresh option.
[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
16 volatile show_early_output_fn_t show_early_output;
17
18 char *path_name(const struct name_path *path, const char *name)
19 {
20         const struct name_path *p;
21         char *n, *m;
22         int nlen = strlen(name);
23         int len = nlen + 1;
24
25         for (p = path; p; p = p->up) {
26                 if (p->elem_len)
27                         len += p->elem_len + 1;
28         }
29         n = xmalloc(len);
30         m = n + len - (nlen + 1);
31         strcpy(m, name);
32         for (p = path; p; p = p->up) {
33                 if (p->elem_len) {
34                         m -= p->elem_len + 1;
35                         memcpy(m, p->elem, p->elem_len);
36                         m[p->elem_len] = '/';
37                 }
38         }
39         return n;
40 }
41
42 void add_object(struct object *obj,
43                 struct object_array *p,
44                 struct name_path *path,
45                 const char *name)
46 {
47         add_object_array(obj, path_name(path, name), p);
48 }
49
50 static void mark_blob_uninteresting(struct blob *blob)
51 {
52         if (!blob)
53                 return;
54         if (blob->object.flags & UNINTERESTING)
55                 return;
56         blob->object.flags |= UNINTERESTING;
57 }
58
59 void mark_tree_uninteresting(struct tree *tree)
60 {
61         struct tree_desc desc;
62         struct name_entry entry;
63         struct object *obj = &tree->object;
64
65         if (!tree)
66                 return;
67         if (obj->flags & UNINTERESTING)
68                 return;
69         obj->flags |= UNINTERESTING;
70         if (!has_sha1_file(obj->sha1))
71                 return;
72         if (parse_tree(tree) < 0)
73                 die("bad tree %s", sha1_to_hex(obj->sha1));
74
75         init_tree_desc(&desc, tree->buffer, tree->size);
76         while (tree_entry(&desc, &entry)) {
77                 switch (object_type(entry.mode)) {
78                 case OBJ_TREE:
79                         mark_tree_uninteresting(lookup_tree(entry.sha1));
80                         break;
81                 case OBJ_BLOB:
82                         mark_blob_uninteresting(lookup_blob(entry.sha1));
83                         break;
84                 default:
85                         /* Subproject commit - not in this repository */
86                         break;
87                 }
88         }
89
90         /*
91          * We don't care about the tree any more
92          * after it has been marked uninteresting.
93          */
94         free(tree->buffer);
95         tree->buffer = NULL;
96 }
97
98 void mark_parents_uninteresting(struct commit *commit)
99 {
100         struct commit_list *parents = commit->parents;
101
102         while (parents) {
103                 struct commit *commit = parents->item;
104                 if (!(commit->object.flags & UNINTERESTING)) {
105                         commit->object.flags |= UNINTERESTING;
106
107                         /*
108                          * Normally we haven't parsed the parent
109                          * yet, so we won't have a parent of a parent
110                          * here. However, it may turn out that we've
111                          * reached this commit some other way (where it
112                          * wasn't uninteresting), in which case we need
113                          * to mark its parents recursively too..
114                          */
115                         if (commit->parents)
116                                 mark_parents_uninteresting(commit);
117                 }
118
119                 /*
120                  * A missing commit is ok iff its parent is marked
121                  * uninteresting.
122                  *
123                  * We just mark such a thing parsed, so that when
124                  * it is popped next time around, we won't be trying
125                  * to parse it and get an error.
126                  */
127                 if (!has_sha1_file(commit->object.sha1))
128                         commit->object.parsed = 1;
129                 parents = parents->next;
130         }
131 }
132
133 static void add_pending_object_with_mode(struct rev_info *revs, struct object *obj, const char *name, unsigned mode)
134 {
135         if (revs->no_walk && (obj->flags & UNINTERESTING))
136                 revs->no_walk = 0;
137         if (revs->reflog_info && obj->type == OBJ_COMMIT &&
138                         add_reflog_for_walk(revs->reflog_info,
139                                 (struct commit *)obj, name))
140                 return;
141         add_object_array_with_mode(obj, name, &revs->pending, mode);
142 }
143
144 void add_pending_object(struct rev_info *revs, struct object *obj, const char *name)
145 {
146         add_pending_object_with_mode(revs, obj, name, S_IFINVALID);
147 }
148
149 void add_head_to_pending(struct rev_info *revs)
150 {
151         unsigned char sha1[20];
152         struct object *obj;
153         if (get_sha1("HEAD", sha1))
154                 return;
155         obj = parse_object(sha1);
156         if (!obj)
157                 return;
158         add_pending_object(revs, obj, "HEAD");
159 }
160
161 static struct object *get_reference(struct rev_info *revs, const char *name, const unsigned char *sha1, unsigned int flags)
162 {
163         struct object *object;
164
165         object = parse_object(sha1);
166         if (!object)
167                 die("bad object %s", name);
168         object->flags |= flags;
169         return object;
170 }
171
172 static struct commit *handle_commit(struct rev_info *revs, struct object *object, const char *name)
173 {
174         unsigned long flags = object->flags;
175
176         /*
177          * Tag object? Look what it points to..
178          */
179         while (object->type == OBJ_TAG) {
180                 struct tag *tag = (struct tag *) object;
181                 if (revs->tag_objects && !(flags & UNINTERESTING))
182                         add_pending_object(revs, object, tag->tag);
183                 if (!tag->tagged)
184                         die("bad tag");
185                 object = parse_object(tag->tagged->sha1);
186                 if (!object) {
187                         if (flags & UNINTERESTING)
188                                 return NULL;
189                         die("bad object %s", sha1_to_hex(tag->tagged->sha1));
190                 }
191         }
192
193         /*
194          * Commit object? Just return it, we'll do all the complex
195          * reachability crud.
196          */
197         if (object->type == OBJ_COMMIT) {
198                 struct commit *commit = (struct commit *)object;
199                 if (parse_commit(commit) < 0)
200                         die("unable to parse commit %s", name);
201                 if (flags & UNINTERESTING) {
202                         commit->object.flags |= UNINTERESTING;
203                         mark_parents_uninteresting(commit);
204                         revs->limited = 1;
205                 }
206                 if (revs->show_source && !commit->util)
207                         commit->util = (void *) name;
208                 return commit;
209         }
210
211         /*
212          * Tree object? Either mark it uninteresting, or add it
213          * to the list of objects to look at later..
214          */
215         if (object->type == OBJ_TREE) {
216                 struct tree *tree = (struct tree *)object;
217                 if (!revs->tree_objects)
218                         return NULL;
219                 if (flags & UNINTERESTING) {
220                         mark_tree_uninteresting(tree);
221                         return NULL;
222                 }
223                 add_pending_object(revs, object, "");
224                 return NULL;
225         }
226
227         /*
228          * Blob object? You know the drill by now..
229          */
230         if (object->type == OBJ_BLOB) {
231                 struct blob *blob = (struct blob *)object;
232                 if (!revs->blob_objects)
233                         return NULL;
234                 if (flags & UNINTERESTING) {
235                         mark_blob_uninteresting(blob);
236                         return NULL;
237                 }
238                 add_pending_object(revs, object, "");
239                 return NULL;
240         }
241         die("%s is unknown object", name);
242 }
243
244 static int everybody_uninteresting(struct commit_list *orig)
245 {
246         struct commit_list *list = orig;
247         while (list) {
248                 struct commit *commit = list->item;
249                 list = list->next;
250                 if (commit->object.flags & UNINTERESTING)
251                         continue;
252                 return 0;
253         }
254         return 1;
255 }
256
257 /*
258  * The goal is to get REV_TREE_NEW as the result only if the
259  * diff consists of all '+' (and no other changes), REV_TREE_OLD
260  * if the whole diff is removal of old data, and otherwise
261  * REV_TREE_DIFFERENT (of course if the trees are the same we
262  * want REV_TREE_SAME).
263  * That means that once we get to REV_TREE_DIFFERENT, we do not
264  * have to look any further.
265  */
266 static int tree_difference = REV_TREE_SAME;
267
268 static void file_add_remove(struct diff_options *options,
269                     int addremove, unsigned mode,
270                     const unsigned char *sha1,
271                     const char *fullpath)
272 {
273         int diff = addremove == '+' ? REV_TREE_NEW : REV_TREE_OLD;
274
275         tree_difference |= diff;
276         if (tree_difference == REV_TREE_DIFFERENT)
277                 DIFF_OPT_SET(options, HAS_CHANGES);
278 }
279
280 static void file_change(struct diff_options *options,
281                  unsigned old_mode, unsigned new_mode,
282                  const unsigned char *old_sha1,
283                  const unsigned char *new_sha1,
284                  const char *fullpath)
285 {
286         tree_difference = REV_TREE_DIFFERENT;
287         DIFF_OPT_SET(options, HAS_CHANGES);
288 }
289
290 static int rev_compare_tree(struct rev_info *revs, struct commit *parent, struct commit *commit)
291 {
292         struct tree *t1 = parent->tree;
293         struct tree *t2 = commit->tree;
294
295         if (!t1)
296                 return REV_TREE_NEW;
297         if (!t2)
298                 return REV_TREE_OLD;
299
300         if (revs->simplify_by_decoration) {
301                 /*
302                  * If we are simplifying by decoration, then the commit
303                  * is worth showing if it has a tag pointing at it.
304                  */
305                 if (lookup_decoration(&name_decoration, &commit->object))
306                         return REV_TREE_DIFFERENT;
307                 /*
308                  * A commit that is not pointed by a tag is uninteresting
309                  * if we are not limited by path.  This means that you will
310                  * see the usual "commits that touch the paths" plus any
311                  * tagged commit by specifying both --simplify-by-decoration
312                  * and pathspec.
313                  */
314                 if (!revs->prune_data)
315                         return REV_TREE_SAME;
316         }
317
318         tree_difference = REV_TREE_SAME;
319         DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
320         if (diff_tree_sha1(t1->object.sha1, t2->object.sha1, "",
321                            &revs->pruning) < 0)
322                 return REV_TREE_DIFFERENT;
323         return tree_difference;
324 }
325
326 static int rev_same_tree_as_empty(struct rev_info *revs, struct commit *commit)
327 {
328         int retval;
329         void *tree;
330         unsigned long size;
331         struct tree_desc empty, real;
332         struct tree *t1 = commit->tree;
333
334         if (!t1)
335                 return 0;
336
337         tree = read_object_with_reference(t1->object.sha1, tree_type, &size, NULL);
338         if (!tree)
339                 return 0;
340         init_tree_desc(&real, tree, size);
341         init_tree_desc(&empty, "", 0);
342
343         tree_difference = REV_TREE_SAME;
344         DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
345         retval = diff_tree(&empty, &real, "", &revs->pruning);
346         free(tree);
347
348         return retval >= 0 && (tree_difference == REV_TREE_SAME);
349 }
350
351 static void try_to_simplify_commit(struct rev_info *revs, struct commit *commit)
352 {
353         struct commit_list **pp, *parent;
354         int tree_changed = 0, tree_same = 0;
355
356         /*
357          * If we don't do pruning, everything is interesting
358          */
359         if (!revs->prune)
360                 return;
361
362         if (!commit->tree)
363                 return;
364
365         if (!commit->parents) {
366                 if (rev_same_tree_as_empty(revs, commit))
367                         commit->object.flags |= TREESAME;
368                 return;
369         }
370
371         /*
372          * Normal non-merge commit? If we don't want to make the
373          * history dense, we consider it always to be a change..
374          */
375         if (!revs->dense && !commit->parents->next)
376                 return;
377
378         pp = &commit->parents;
379         while ((parent = *pp) != NULL) {
380                 struct commit *p = parent->item;
381
382                 if (parse_commit(p) < 0)
383                         die("cannot simplify commit %s (because of %s)",
384                             sha1_to_hex(commit->object.sha1),
385                             sha1_to_hex(p->object.sha1));
386                 switch (rev_compare_tree(revs, p, commit)) {
387                 case REV_TREE_SAME:
388                         tree_same = 1;
389                         if (!revs->simplify_history || (p->object.flags & UNINTERESTING)) {
390                                 /* Even if a merge with an uninteresting
391                                  * side branch brought the entire change
392                                  * we are interested in, we do not want
393                                  * to lose the other branches of this
394                                  * merge, so we just keep going.
395                                  */
396                                 pp = &parent->next;
397                                 continue;
398                         }
399                         parent->next = NULL;
400                         commit->parents = parent;
401                         commit->object.flags |= TREESAME;
402                         return;
403
404                 case REV_TREE_NEW:
405                         if (revs->remove_empty_trees &&
406                             rev_same_tree_as_empty(revs, p)) {
407                                 /* We are adding all the specified
408                                  * paths from this parent, so the
409                                  * history beyond this parent is not
410                                  * interesting.  Remove its parents
411                                  * (they are grandparents for us).
412                                  * IOW, we pretend this parent is a
413                                  * "root" commit.
414                                  */
415                                 if (parse_commit(p) < 0)
416                                         die("cannot simplify commit %s (invalid %s)",
417                                             sha1_to_hex(commit->object.sha1),
418                                             sha1_to_hex(p->object.sha1));
419                                 p->parents = NULL;
420                         }
421                 /* fallthrough */
422                 case REV_TREE_OLD:
423                 case REV_TREE_DIFFERENT:
424                         tree_changed = 1;
425                         pp = &parent->next;
426                         continue;
427                 }
428                 die("bad tree compare for commit %s", sha1_to_hex(commit->object.sha1));
429         }
430         if (tree_changed && !tree_same)
431                 return;
432         commit->object.flags |= TREESAME;
433 }
434
435 static void insert_by_date_cached(struct commit *p, struct commit_list **head,
436                     struct commit_list *cached_base, struct commit_list **cache)
437 {
438         struct commit_list *new_entry;
439
440         if (cached_base && p->date < cached_base->item->date)
441                 new_entry = insert_by_date(p, &cached_base->next);
442         else
443                 new_entry = insert_by_date(p, head);
444
445         if (cache && (!*cache || p->date < (*cache)->item->date))
446                 *cache = new_entry;
447 }
448
449 static int add_parents_to_list(struct rev_info *revs, struct commit *commit,
450                     struct commit_list **list, struct commit_list **cache_ptr)
451 {
452         struct commit_list *parent = commit->parents;
453         unsigned left_flag;
454         struct commit_list *cached_base = cache_ptr ? *cache_ptr : NULL;
455
456         if (commit->object.flags & ADDED)
457                 return 0;
458         commit->object.flags |= ADDED;
459
460         /*
461          * If the commit is uninteresting, don't try to
462          * prune parents - we want the maximal uninteresting
463          * set.
464          *
465          * Normally we haven't parsed the parent
466          * yet, so we won't have a parent of a parent
467          * here. However, it may turn out that we've
468          * reached this commit some other way (where it
469          * wasn't uninteresting), in which case we need
470          * to mark its parents recursively too..
471          */
472         if (commit->object.flags & UNINTERESTING) {
473                 while (parent) {
474                         struct commit *p = parent->item;
475                         parent = parent->next;
476                         if (p)
477                                 p->object.flags |= UNINTERESTING;
478                         if (parse_commit(p) < 0)
479                                 continue;
480                         if (p->parents)
481                                 mark_parents_uninteresting(p);
482                         if (p->object.flags & SEEN)
483                                 continue;
484                         p->object.flags |= SEEN;
485                         insert_by_date_cached(p, list, cached_base, cache_ptr);
486                 }
487                 return 0;
488         }
489
490         /*
491          * Ok, the commit wasn't uninteresting. Try to
492          * simplify the commit history and find the parent
493          * that has no differences in the path set if one exists.
494          */
495         try_to_simplify_commit(revs, commit);
496
497         if (revs->no_walk)
498                 return 0;
499
500         left_flag = (commit->object.flags & SYMMETRIC_LEFT);
501
502         for (parent = commit->parents; parent; parent = parent->next) {
503                 struct commit *p = parent->item;
504
505                 if (parse_commit(p) < 0)
506                         return -1;
507                 if (revs->show_source && !p->util)
508                         p->util = commit->util;
509                 p->object.flags |= left_flag;
510                 if (!(p->object.flags & SEEN)) {
511                         p->object.flags |= SEEN;
512                         insert_by_date_cached(p, list, cached_base, cache_ptr);
513                 }
514                 if (revs->first_parent_only)
515                         break;
516         }
517         return 0;
518 }
519
520 static void cherry_pick_list(struct commit_list *list, struct rev_info *revs)
521 {
522         struct commit_list *p;
523         int left_count = 0, right_count = 0;
524         int left_first;
525         struct patch_ids ids;
526
527         /* First count the commits on the left and on the right */
528         for (p = list; p; p = p->next) {
529                 struct commit *commit = p->item;
530                 unsigned flags = commit->object.flags;
531                 if (flags & BOUNDARY)
532                         ;
533                 else if (flags & SYMMETRIC_LEFT)
534                         left_count++;
535                 else
536                         right_count++;
537         }
538
539         left_first = left_count < right_count;
540         init_patch_ids(&ids);
541         if (revs->diffopt.nr_paths) {
542                 ids.diffopts.nr_paths = revs->diffopt.nr_paths;
543                 ids.diffopts.paths = revs->diffopt.paths;
544                 ids.diffopts.pathlens = revs->diffopt.pathlens;
545         }
546
547         /* Compute patch-ids for one side */
548         for (p = list; p; p = p->next) {
549                 struct commit *commit = p->item;
550                 unsigned flags = commit->object.flags;
551
552                 if (flags & BOUNDARY)
553                         continue;
554                 /*
555                  * If we have fewer left, left_first is set and we omit
556                  * commits on the right branch in this loop.  If we have
557                  * fewer right, we skip the left ones.
558                  */
559                 if (left_first != !!(flags & SYMMETRIC_LEFT))
560                         continue;
561                 commit->util = add_commit_patch_id(commit, &ids);
562         }
563
564         /* Check the other side */
565         for (p = list; p; p = p->next) {
566                 struct commit *commit = p->item;
567                 struct patch_id *id;
568                 unsigned flags = commit->object.flags;
569
570                 if (flags & BOUNDARY)
571                         continue;
572                 /*
573                  * If we have fewer left, left_first is set and we omit
574                  * commits on the left branch in this loop.
575                  */
576                 if (left_first == !!(flags & SYMMETRIC_LEFT))
577                         continue;
578
579                 /*
580                  * Have we seen the same patch id?
581                  */
582                 id = has_commit_patch_id(commit, &ids);
583                 if (!id)
584                         continue;
585                 id->seen = 1;
586                 commit->object.flags |= SHOWN;
587         }
588
589         /* Now check the original side for seen ones */
590         for (p = list; p; p = p->next) {
591                 struct commit *commit = p->item;
592                 struct patch_id *ent;
593
594                 ent = commit->util;
595                 if (!ent)
596                         continue;
597                 if (ent->seen)
598                         commit->object.flags |= SHOWN;
599                 commit->util = NULL;
600         }
601
602         free_patch_ids(&ids);
603 }
604
605 /* How many extra uninteresting commits we want to see.. */
606 #define SLOP 5
607
608 static int still_interesting(struct commit_list *src, unsigned long date, int slop)
609 {
610         /*
611          * No source list at all? We're definitely done..
612          */
613         if (!src)
614                 return 0;
615
616         /*
617          * Does the destination list contain entries with a date
618          * before the source list? Definitely _not_ done.
619          */
620         if (date < src->item->date)
621                 return SLOP;
622
623         /*
624          * Does the source list still have interesting commits in
625          * it? Definitely not done..
626          */
627         if (!everybody_uninteresting(src))
628                 return SLOP;
629
630         /* Ok, we're closing in.. */
631         return slop-1;
632 }
633
634 static int limit_list(struct rev_info *revs)
635 {
636         int slop = SLOP;
637         unsigned long date = ~0ul;
638         struct commit_list *list = revs->commits;
639         struct commit_list *newlist = NULL;
640         struct commit_list **p = &newlist;
641
642         while (list) {
643                 struct commit_list *entry = list;
644                 struct commit *commit = list->item;
645                 struct object *obj = &commit->object;
646                 show_early_output_fn_t show;
647
648                 list = list->next;
649                 free(entry);
650
651                 if (revs->max_age != -1 && (commit->date < revs->max_age))
652                         obj->flags |= UNINTERESTING;
653                 if (add_parents_to_list(revs, commit, &list, NULL) < 0)
654                         return -1;
655                 if (obj->flags & UNINTERESTING) {
656                         mark_parents_uninteresting(commit);
657                         if (revs->show_all)
658                                 p = &commit_list_insert(commit, p)->next;
659                         slop = still_interesting(list, date, slop);
660                         if (slop)
661                                 continue;
662                         /* If showing all, add the whole pending list to the end */
663                         if (revs->show_all)
664                                 *p = list;
665                         break;
666                 }
667                 if (revs->min_age != -1 && (commit->date > revs->min_age))
668                         continue;
669                 date = commit->date;
670                 p = &commit_list_insert(commit, p)->next;
671
672                 show = show_early_output;
673                 if (!show)
674                         continue;
675
676                 show(revs, newlist);
677                 show_early_output = NULL;
678         }
679         if (revs->cherry_pick)
680                 cherry_pick_list(newlist, revs);
681
682         revs->commits = newlist;
683         return 0;
684 }
685
686 struct all_refs_cb {
687         int all_flags;
688         int warned_bad_reflog;
689         struct rev_info *all_revs;
690         const char *name_for_errormsg;
691 };
692
693 static int handle_one_ref(const char *path, const unsigned char *sha1, int flag, void *cb_data)
694 {
695         struct all_refs_cb *cb = cb_data;
696         struct object *object = get_reference(cb->all_revs, path, sha1,
697                                               cb->all_flags);
698         add_pending_object(cb->all_revs, object, path);
699         return 0;
700 }
701
702 static void handle_refs(struct rev_info *revs, unsigned flags,
703                 int (*for_each)(each_ref_fn, void *))
704 {
705         struct all_refs_cb cb;
706         cb.all_revs = revs;
707         cb.all_flags = flags;
708         for_each(handle_one_ref, &cb);
709 }
710
711 static void handle_one_reflog_commit(unsigned char *sha1, void *cb_data)
712 {
713         struct all_refs_cb *cb = cb_data;
714         if (!is_null_sha1(sha1)) {
715                 struct object *o = parse_object(sha1);
716                 if (o) {
717                         o->flags |= cb->all_flags;
718                         add_pending_object(cb->all_revs, o, "");
719                 }
720                 else if (!cb->warned_bad_reflog) {
721                         warning("reflog of '%s' references pruned commits",
722                                 cb->name_for_errormsg);
723                         cb->warned_bad_reflog = 1;
724                 }
725         }
726 }
727
728 static int handle_one_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
729                 const char *email, unsigned long timestamp, int tz,
730                 const char *message, void *cb_data)
731 {
732         handle_one_reflog_commit(osha1, cb_data);
733         handle_one_reflog_commit(nsha1, cb_data);
734         return 0;
735 }
736
737 static int handle_one_reflog(const char *path, const unsigned char *sha1, int flag, void *cb_data)
738 {
739         struct all_refs_cb *cb = cb_data;
740         cb->warned_bad_reflog = 0;
741         cb->name_for_errormsg = path;
742         for_each_reflog_ent(path, handle_one_reflog_ent, cb_data);
743         return 0;
744 }
745
746 static void handle_reflog(struct rev_info *revs, unsigned flags)
747 {
748         struct all_refs_cb cb;
749         cb.all_revs = revs;
750         cb.all_flags = flags;
751         for_each_reflog(handle_one_reflog, &cb);
752 }
753
754 static int add_parents_only(struct rev_info *revs, const char *arg, int flags)
755 {
756         unsigned char sha1[20];
757         struct object *it;
758         struct commit *commit;
759         struct commit_list *parents;
760
761         if (*arg == '^') {
762                 flags ^= UNINTERESTING;
763                 arg++;
764         }
765         if (get_sha1(arg, sha1))
766                 return 0;
767         while (1) {
768                 it = get_reference(revs, arg, sha1, 0);
769                 if (it->type != OBJ_TAG)
770                         break;
771                 if (!((struct tag*)it)->tagged)
772                         return 0;
773                 hashcpy(sha1, ((struct tag*)it)->tagged->sha1);
774         }
775         if (it->type != OBJ_COMMIT)
776                 return 0;
777         commit = (struct commit *)it;
778         for (parents = commit->parents; parents; parents = parents->next) {
779                 it = &parents->item->object;
780                 it->flags |= flags;
781                 add_pending_object(revs, it, arg);
782         }
783         return 1;
784 }
785
786 void init_revisions(struct rev_info *revs, const char *prefix)
787 {
788         memset(revs, 0, sizeof(*revs));
789
790         revs->abbrev = DEFAULT_ABBREV;
791         revs->ignore_merges = 1;
792         revs->simplify_history = 1;
793         DIFF_OPT_SET(&revs->pruning, RECURSIVE);
794         DIFF_OPT_SET(&revs->pruning, QUIET);
795         revs->pruning.add_remove = file_add_remove;
796         revs->pruning.change = file_change;
797         revs->lifo = 1;
798         revs->dense = 1;
799         revs->prefix = prefix;
800         revs->max_age = -1;
801         revs->min_age = -1;
802         revs->skip_count = -1;
803         revs->max_count = -1;
804
805         revs->commit_format = CMIT_FMT_DEFAULT;
806
807         revs->grep_filter.status_only = 1;
808         revs->grep_filter.pattern_tail = &(revs->grep_filter.pattern_list);
809         revs->grep_filter.regflags = REG_NEWLINE;
810
811         diff_setup(&revs->diffopt);
812         if (prefix && !revs->diffopt.prefix) {
813                 revs->diffopt.prefix = prefix;
814                 revs->diffopt.prefix_length = strlen(prefix);
815         }
816 }
817
818 static void add_pending_commit_list(struct rev_info *revs,
819                                     struct commit_list *commit_list,
820                                     unsigned int flags)
821 {
822         while (commit_list) {
823                 struct object *object = &commit_list->item->object;
824                 object->flags |= flags;
825                 add_pending_object(revs, object, sha1_to_hex(object->sha1));
826                 commit_list = commit_list->next;
827         }
828 }
829
830 static void prepare_show_merge(struct rev_info *revs)
831 {
832         struct commit_list *bases;
833         struct commit *head, *other;
834         unsigned char sha1[20];
835         const char **prune = NULL;
836         int i, prune_num = 1; /* counting terminating NULL */
837
838         if (get_sha1("HEAD", sha1) || !(head = lookup_commit(sha1)))
839                 die("--merge without HEAD?");
840         if (get_sha1("MERGE_HEAD", sha1) || !(other = lookup_commit(sha1)))
841                 die("--merge without MERGE_HEAD?");
842         add_pending_object(revs, &head->object, "HEAD");
843         add_pending_object(revs, &other->object, "MERGE_HEAD");
844         bases = get_merge_bases(head, other, 1);
845         add_pending_commit_list(revs, bases, UNINTERESTING);
846         free_commit_list(bases);
847         head->object.flags |= SYMMETRIC_LEFT;
848
849         if (!active_nr)
850                 read_cache();
851         for (i = 0; i < active_nr; i++) {
852                 struct cache_entry *ce = active_cache[i];
853                 if (!ce_stage(ce))
854                         continue;
855                 if (ce_path_match(ce, revs->prune_data)) {
856                         prune_num++;
857                         prune = xrealloc(prune, sizeof(*prune) * prune_num);
858                         prune[prune_num-2] = ce->name;
859                         prune[prune_num-1] = NULL;
860                 }
861                 while ((i+1 < active_nr) &&
862                        ce_same_name(ce, active_cache[i+1]))
863                         i++;
864         }
865         revs->prune_data = prune;
866         revs->limited = 1;
867 }
868
869 int handle_revision_arg(const char *arg, struct rev_info *revs,
870                         int flags,
871                         int cant_be_filename)
872 {
873         unsigned mode;
874         char *dotdot;
875         struct object *object;
876         unsigned char sha1[20];
877         int local_flags;
878
879         dotdot = strstr(arg, "..");
880         if (dotdot) {
881                 unsigned char from_sha1[20];
882                 const char *next = dotdot + 2;
883                 const char *this = arg;
884                 int symmetric = *next == '.';
885                 unsigned int flags_exclude = flags ^ UNINTERESTING;
886
887                 *dotdot = 0;
888                 next += symmetric;
889
890                 if (!*next)
891                         next = "HEAD";
892                 if (dotdot == arg)
893                         this = "HEAD";
894                 if (!get_sha1(this, from_sha1) &&
895                     !get_sha1(next, sha1)) {
896                         struct commit *a, *b;
897                         struct commit_list *exclude;
898
899                         a = lookup_commit_reference(from_sha1);
900                         b = lookup_commit_reference(sha1);
901                         if (!a || !b) {
902                                 die(symmetric ?
903                                     "Invalid symmetric difference expression %s...%s" :
904                                     "Invalid revision range %s..%s",
905                                     arg, next);
906                         }
907
908                         if (!cant_be_filename) {
909                                 *dotdot = '.';
910                                 verify_non_filename(revs->prefix, arg);
911                         }
912
913                         if (symmetric) {
914                                 exclude = get_merge_bases(a, b, 1);
915                                 add_pending_commit_list(revs, exclude,
916                                                         flags_exclude);
917                                 free_commit_list(exclude);
918                                 a->object.flags |= flags | SYMMETRIC_LEFT;
919                         } else
920                                 a->object.flags |= flags_exclude;
921                         b->object.flags |= flags;
922                         add_pending_object(revs, &a->object, this);
923                         add_pending_object(revs, &b->object, next);
924                         return 0;
925                 }
926                 *dotdot = '.';
927         }
928         dotdot = strstr(arg, "^@");
929         if (dotdot && !dotdot[2]) {
930                 *dotdot = 0;
931                 if (add_parents_only(revs, arg, flags))
932                         return 0;
933                 *dotdot = '^';
934         }
935         dotdot = strstr(arg, "^!");
936         if (dotdot && !dotdot[2]) {
937                 *dotdot = 0;
938                 if (!add_parents_only(revs, arg, flags ^ UNINTERESTING))
939                         *dotdot = '^';
940         }
941
942         local_flags = 0;
943         if (*arg == '^') {
944                 local_flags = UNINTERESTING;
945                 arg++;
946         }
947         if (get_sha1_with_mode(arg, sha1, &mode))
948                 return -1;
949         if (!cant_be_filename)
950                 verify_non_filename(revs->prefix, arg);
951         object = get_reference(revs, arg, sha1, flags ^ local_flags);
952         add_pending_object_with_mode(revs, object, arg, mode);
953         return 0;
954 }
955
956 void read_revisions_from_stdin(struct rev_info *revs)
957 {
958         char line[1000];
959
960         while (fgets(line, sizeof(line), stdin) != NULL) {
961                 int len = strlen(line);
962                 if (len && line[len - 1] == '\n')
963                         line[--len] = '\0';
964                 if (!len)
965                         break;
966                 if (line[0] == '-')
967                         die("options not supported in --stdin mode");
968                 if (handle_revision_arg(line, revs, 0, 1))
969                         die("bad revision '%s'", line);
970         }
971 }
972
973 static void add_grep(struct rev_info *revs, const char *ptn, enum grep_pat_token what)
974 {
975         append_grep_pattern(&revs->grep_filter, ptn, "command line", 0, what);
976 }
977
978 static void add_header_grep(struct rev_info *revs, enum grep_header_field field, const char *pattern)
979 {
980         append_header_grep_pattern(&revs->grep_filter, field, pattern);
981 }
982
983 static void add_message_grep(struct rev_info *revs, const char *pattern)
984 {
985         add_grep(revs, pattern, GREP_PATTERN_BODY);
986 }
987
988 static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv,
989                                int *unkc, const char **unkv)
990 {
991         const char *arg = argv[0];
992
993         /* pseudo revision arguments */
994         if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") ||
995             !strcmp(arg, "--tags") || !strcmp(arg, "--remotes") ||
996             !strcmp(arg, "--reflog") || !strcmp(arg, "--not") ||
997             !strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk"))
998         {
999                 unkv[(*unkc)++] = arg;
1000                 return 1;
1001         }
1002
1003         if (!prefixcmp(arg, "--max-count=")) {
1004                 revs->max_count = atoi(arg + 12);
1005         } else if (!prefixcmp(arg, "--skip=")) {
1006                 revs->skip_count = atoi(arg + 7);
1007         } else if ((*arg == '-') && isdigit(arg[1])) {
1008         /* accept -<digit>, like traditional "head" */
1009                 revs->max_count = atoi(arg + 1);
1010         } else if (!strcmp(arg, "-n")) {
1011                 if (argc <= 1)
1012                         return error("-n requires an argument");
1013                 revs->max_count = atoi(argv[1]);
1014                 return 2;
1015         } else if (!prefixcmp(arg, "-n")) {
1016                 revs->max_count = atoi(arg + 2);
1017         } else if (!prefixcmp(arg, "--max-age=")) {
1018                 revs->max_age = atoi(arg + 10);
1019         } else if (!prefixcmp(arg, "--since=")) {
1020                 revs->max_age = approxidate(arg + 8);
1021         } else if (!prefixcmp(arg, "--after=")) {
1022                 revs->max_age = approxidate(arg + 8);
1023         } else if (!prefixcmp(arg, "--min-age=")) {
1024                 revs->min_age = atoi(arg + 10);
1025         } else if (!prefixcmp(arg, "--before=")) {
1026                 revs->min_age = approxidate(arg + 9);
1027         } else if (!prefixcmp(arg, "--until=")) {
1028                 revs->min_age = approxidate(arg + 8);
1029         } else if (!strcmp(arg, "--first-parent")) {
1030                 revs->first_parent_only = 1;
1031         } else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) {
1032                 init_reflog_walk(&revs->reflog_info);
1033         } else if (!strcmp(arg, "--default")) {
1034                 if (argc <= 1)
1035                         return error("bad --default argument");
1036                 revs->def = argv[1];
1037                 return 2;
1038         } else if (!strcmp(arg, "--merge")) {
1039                 revs->show_merge = 1;
1040         } else if (!strcmp(arg, "--topo-order")) {
1041                 revs->lifo = 1;
1042                 revs->topo_order = 1;
1043         } else if (!strcmp(arg, "--simplify-merges")) {
1044                 revs->simplify_merges = 1;
1045                 revs->rewrite_parents = 1;
1046                 revs->simplify_history = 0;
1047                 revs->limited = 1;
1048         } else if (!strcmp(arg, "--simplify-by-decoration")) {
1049                 revs->simplify_merges = 1;
1050                 revs->rewrite_parents = 1;
1051                 revs->simplify_history = 0;
1052                 revs->simplify_by_decoration = 1;
1053                 revs->limited = 1;
1054                 revs->prune = 1;
1055                 load_ref_decorations(DECORATE_SHORT_REFS);
1056         } else if (!strcmp(arg, "--date-order")) {
1057                 revs->lifo = 0;
1058                 revs->topo_order = 1;
1059         } else if (!prefixcmp(arg, "--early-output")) {
1060                 int count = 100;
1061                 switch (arg[14]) {
1062                 case '=':
1063                         count = atoi(arg+15);
1064                         /* Fallthrough */
1065                 case 0:
1066                         revs->topo_order = 1;
1067                        revs->early_output = count;
1068                 }
1069         } else if (!strcmp(arg, "--parents")) {
1070                 revs->rewrite_parents = 1;
1071                 revs->print_parents = 1;
1072         } else if (!strcmp(arg, "--dense")) {
1073                 revs->dense = 1;
1074         } else if (!strcmp(arg, "--sparse")) {
1075                 revs->dense = 0;
1076         } else if (!strcmp(arg, "--show-all")) {
1077                 revs->show_all = 1;
1078         } else if (!strcmp(arg, "--remove-empty")) {
1079                 revs->remove_empty_trees = 1;
1080         } else if (!strcmp(arg, "--merges")) {
1081                 revs->merges_only = 1;
1082         } else if (!strcmp(arg, "--no-merges")) {
1083                 revs->no_merges = 1;
1084         } else if (!strcmp(arg, "--boundary")) {
1085                 revs->boundary = 1;
1086         } else if (!strcmp(arg, "--left-right")) {
1087                 revs->left_right = 1;
1088         } else if (!strcmp(arg, "--cherry-pick")) {
1089                 revs->cherry_pick = 1;
1090                 revs->limited = 1;
1091         } else if (!strcmp(arg, "--objects")) {
1092                 revs->tag_objects = 1;
1093                 revs->tree_objects = 1;
1094                 revs->blob_objects = 1;
1095         } else if (!strcmp(arg, "--objects-edge")) {
1096                 revs->tag_objects = 1;
1097                 revs->tree_objects = 1;
1098                 revs->blob_objects = 1;
1099                 revs->edge_hint = 1;
1100         } else if (!strcmp(arg, "--unpacked")) {
1101                 revs->unpacked = 1;
1102         } else if (!prefixcmp(arg, "--unpacked=")) {
1103                 die("--unpacked=<packfile> no longer supported.");
1104         } else if (!strcmp(arg, "-r")) {
1105                 revs->diff = 1;
1106                 DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
1107         } else if (!strcmp(arg, "-t")) {
1108                 revs->diff = 1;
1109                 DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
1110                 DIFF_OPT_SET(&revs->diffopt, TREE_IN_RECURSIVE);
1111         } else if (!strcmp(arg, "-m")) {
1112                 revs->ignore_merges = 0;
1113         } else if (!strcmp(arg, "-c")) {
1114                 revs->diff = 1;
1115                 revs->dense_combined_merges = 0;
1116                 revs->combine_merges = 1;
1117         } else if (!strcmp(arg, "--cc")) {
1118                 revs->diff = 1;
1119                 revs->dense_combined_merges = 1;
1120                 revs->combine_merges = 1;
1121         } else if (!strcmp(arg, "-v")) {
1122                 revs->verbose_header = 1;
1123         } else if (!strcmp(arg, "--pretty")) {
1124                 revs->verbose_header = 1;
1125                 get_commit_format(arg+8, revs);
1126         } else if (!prefixcmp(arg, "--pretty=") || !prefixcmp(arg, "--format=")) {
1127                 revs->verbose_header = 1;
1128                 get_commit_format(arg+9, revs);
1129         } else if (!strcmp(arg, "--oneline")) {
1130                 revs->verbose_header = 1;
1131                 get_commit_format("oneline", revs);
1132                 revs->abbrev_commit = 1;
1133         } else if (!strcmp(arg, "--graph")) {
1134                 revs->topo_order = 1;
1135                 revs->rewrite_parents = 1;
1136                 revs->graph = graph_init(revs);
1137         } else if (!strcmp(arg, "--root")) {
1138                 revs->show_root_diff = 1;
1139         } else if (!strcmp(arg, "--no-commit-id")) {
1140                 revs->no_commit_id = 1;
1141         } else if (!strcmp(arg, "--always")) {
1142                 revs->always_show_header = 1;
1143         } else if (!strcmp(arg, "--no-abbrev")) {
1144                 revs->abbrev = 0;
1145         } else if (!strcmp(arg, "--abbrev")) {
1146                 revs->abbrev = DEFAULT_ABBREV;
1147         } else if (!prefixcmp(arg, "--abbrev=")) {
1148                 revs->abbrev = strtoul(arg + 9, NULL, 10);
1149                 if (revs->abbrev < MINIMUM_ABBREV)
1150                         revs->abbrev = MINIMUM_ABBREV;
1151                 else if (revs->abbrev > 40)
1152                         revs->abbrev = 40;
1153         } else if (!strcmp(arg, "--abbrev-commit")) {
1154                 revs->abbrev_commit = 1;
1155         } else if (!strcmp(arg, "--full-diff")) {
1156                 revs->diff = 1;
1157                 revs->full_diff = 1;
1158         } else if (!strcmp(arg, "--full-history")) {
1159                 revs->simplify_history = 0;
1160         } else if (!strcmp(arg, "--relative-date")) {
1161                 revs->date_mode = DATE_RELATIVE;
1162                 revs->date_mode_explicit = 1;
1163         } else if (!strncmp(arg, "--date=", 7)) {
1164                 revs->date_mode = parse_date_format(arg + 7);
1165                 revs->date_mode_explicit = 1;
1166         } else if (!strcmp(arg, "--log-size")) {
1167                 revs->show_log_size = 1;
1168         }
1169         /*
1170          * Grepping the commit log
1171          */
1172         else if (!prefixcmp(arg, "--author=")) {
1173                 add_header_grep(revs, GREP_HEADER_AUTHOR, arg+9);
1174         } else if (!prefixcmp(arg, "--committer=")) {
1175                 add_header_grep(revs, GREP_HEADER_COMMITTER, arg+12);
1176         } else if (!prefixcmp(arg, "--grep=")) {
1177                 add_message_grep(revs, arg+7);
1178         } else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) {
1179                 revs->grep_filter.regflags |= REG_EXTENDED;
1180         } else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) {
1181                 revs->grep_filter.regflags |= REG_ICASE;
1182         } else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) {
1183                 revs->grep_filter.fixed = 1;
1184         } else if (!strcmp(arg, "--all-match")) {
1185                 revs->grep_filter.all_match = 1;
1186         } else if (!prefixcmp(arg, "--encoding=")) {
1187                 arg += 11;
1188                 if (strcmp(arg, "none"))
1189                         git_log_output_encoding = xstrdup(arg);
1190                 else
1191                         git_log_output_encoding = "";
1192         } else if (!strcmp(arg, "--reverse")) {
1193                 revs->reverse ^= 1;
1194         } else if (!strcmp(arg, "--children")) {
1195                 revs->children.name = "children";
1196                 revs->limited = 1;
1197         } else {
1198                 int opts = diff_opt_parse(&revs->diffopt, argv, argc);
1199                 if (!opts)
1200                         unkv[(*unkc)++] = arg;
1201                 return opts;
1202         }
1203
1204         return 1;
1205 }
1206
1207 void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx,
1208                         const struct option *options,
1209                         const char * const usagestr[])
1210 {
1211         int n = handle_revision_opt(revs, ctx->argc, ctx->argv,
1212                                     &ctx->cpidx, ctx->out);
1213         if (n <= 0) {
1214                 error("unknown option `%s'", ctx->argv[0]);
1215                 usage_with_options(usagestr, options);
1216         }
1217         ctx->argv += n;
1218         ctx->argc -= n;
1219 }
1220
1221 /*
1222  * Parse revision information, filling in the "rev_info" structure,
1223  * and removing the used arguments from the argument list.
1224  *
1225  * Returns the number of arguments left that weren't recognized
1226  * (which are also moved to the head of the argument list)
1227  */
1228 int setup_revisions(int argc, const char **argv, struct rev_info *revs, const char *def)
1229 {
1230         int i, flags, left, seen_dashdash;
1231
1232         /* First, search for "--" */
1233         seen_dashdash = 0;
1234         for (i = 1; i < argc; i++) {
1235                 const char *arg = argv[i];
1236                 if (strcmp(arg, "--"))
1237                         continue;
1238                 argv[i] = NULL;
1239                 argc = i;
1240                 if (argv[i + 1])
1241                         revs->prune_data = get_pathspec(revs->prefix, argv + i + 1);
1242                 seen_dashdash = 1;
1243                 break;
1244         }
1245
1246         /* Second, deal with arguments and options */
1247         flags = 0;
1248         for (left = i = 1; i < argc; i++) {
1249                 const char *arg = argv[i];
1250                 if (*arg == '-') {
1251                         int opts;
1252
1253                         if (!strcmp(arg, "--all")) {
1254                                 handle_refs(revs, flags, for_each_ref);
1255                                 handle_refs(revs, flags, head_ref);
1256                                 continue;
1257                         }
1258                         if (!strcmp(arg, "--branches")) {
1259                                 handle_refs(revs, flags, for_each_branch_ref);
1260                                 continue;
1261                         }
1262                         if (!strcmp(arg, "--tags")) {
1263                                 handle_refs(revs, flags, for_each_tag_ref);
1264                                 continue;
1265                         }
1266                         if (!strcmp(arg, "--remotes")) {
1267                                 handle_refs(revs, flags, for_each_remote_ref);
1268                                 continue;
1269                         }
1270                         if (!strcmp(arg, "--reflog")) {
1271                                 handle_reflog(revs, flags);
1272                                 continue;
1273                         }
1274                         if (!strcmp(arg, "--not")) {
1275                                 flags ^= UNINTERESTING;
1276                                 continue;
1277                         }
1278                         if (!strcmp(arg, "--no-walk")) {
1279                                 revs->no_walk = 1;
1280                                 continue;
1281                         }
1282                         if (!strcmp(arg, "--do-walk")) {
1283                                 revs->no_walk = 0;
1284                                 continue;
1285                         }
1286
1287                         opts = handle_revision_opt(revs, argc - i, argv + i, &left, argv);
1288                         if (opts > 0) {
1289                                 i += opts - 1;
1290                                 continue;
1291                         }
1292                         if (opts < 0)
1293                                 exit(128);
1294                         continue;
1295                 }
1296
1297                 if (handle_revision_arg(arg, revs, flags, seen_dashdash)) {
1298                         int j;
1299                         if (seen_dashdash || *arg == '^')
1300                                 die("bad revision '%s'", arg);
1301
1302                         /* If we didn't have a "--":
1303                          * (1) all filenames must exist;
1304                          * (2) all rev-args must not be interpretable
1305                          *     as a valid filename.
1306                          * but the latter we have checked in the main loop.
1307                          */
1308                         for (j = i; j < argc; j++)
1309                                 verify_filename(revs->prefix, argv[j]);
1310
1311                         revs->prune_data = get_pathspec(revs->prefix,
1312                                                         argv + i);
1313                         break;
1314                 }
1315         }
1316
1317         if (revs->def == NULL)
1318                 revs->def = def;
1319         if (revs->show_merge)
1320                 prepare_show_merge(revs);
1321         if (revs->def && !revs->pending.nr) {
1322                 unsigned char sha1[20];
1323                 struct object *object;
1324                 unsigned mode;
1325                 if (get_sha1_with_mode(revs->def, sha1, &mode))
1326                         die("bad default revision '%s'", revs->def);
1327                 object = get_reference(revs, revs->def, sha1, 0);
1328                 add_pending_object_with_mode(revs, object, revs->def, mode);
1329         }
1330
1331         /* Did the user ask for any diff output? Run the diff! */
1332         if (revs->diffopt.output_format & ~DIFF_FORMAT_NO_OUTPUT)
1333                 revs->diff = 1;
1334
1335         /* Pickaxe, diff-filter and rename following need diffs */
1336         if (revs->diffopt.pickaxe ||
1337             revs->diffopt.filter ||
1338             DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
1339                 revs->diff = 1;
1340
1341         if (revs->topo_order)
1342                 revs->limited = 1;
1343
1344         if (revs->prune_data) {
1345                 diff_tree_setup_paths(revs->prune_data, &revs->pruning);
1346                 /* Can't prune commits with rename following: the paths change.. */
1347                 if (!DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
1348                         revs->prune = 1;
1349                 if (!revs->full_diff)
1350                         diff_tree_setup_paths(revs->prune_data, &revs->diffopt);
1351         }
1352         if (revs->combine_merges) {
1353                 revs->ignore_merges = 0;
1354                 if (revs->dense_combined_merges && !revs->diffopt.output_format)
1355                         revs->diffopt.output_format = DIFF_FORMAT_PATCH;
1356         }
1357         revs->diffopt.abbrev = revs->abbrev;
1358         if (diff_setup_done(&revs->diffopt) < 0)
1359                 die("diff_setup_done failed");
1360
1361         compile_grep_patterns(&revs->grep_filter);
1362
1363         if (revs->reverse && revs->reflog_info)
1364                 die("cannot combine --reverse with --walk-reflogs");
1365         if (revs->rewrite_parents && revs->children.name)
1366                 die("cannot combine --parents and --children");
1367
1368         /*
1369          * Limitations on the graph functionality
1370          */
1371         if (revs->reverse && revs->graph)
1372                 die("cannot combine --reverse with --graph");
1373
1374         if (revs->reflog_info && revs->graph)
1375                 die("cannot combine --walk-reflogs with --graph");
1376
1377         return left;
1378 }
1379
1380 static void add_child(struct rev_info *revs, struct commit *parent, struct commit *child)
1381 {
1382         struct commit_list *l = xcalloc(1, sizeof(*l));
1383
1384         l->item = child;
1385         l->next = add_decoration(&revs->children, &parent->object, l);
1386 }
1387
1388 static int remove_duplicate_parents(struct commit *commit)
1389 {
1390         struct commit_list **pp, *p;
1391         int surviving_parents;
1392
1393         /* Examine existing parents while marking ones we have seen... */
1394         pp = &commit->parents;
1395         while ((p = *pp) != NULL) {
1396                 struct commit *parent = p->item;
1397                 if (parent->object.flags & TMP_MARK) {
1398                         *pp = p->next;
1399                         continue;
1400                 }
1401                 parent->object.flags |= TMP_MARK;
1402                 pp = &p->next;
1403         }
1404         /* count them while clearing the temporary mark */
1405         surviving_parents = 0;
1406         for (p = commit->parents; p; p = p->next) {
1407                 p->item->object.flags &= ~TMP_MARK;
1408                 surviving_parents++;
1409         }
1410         return surviving_parents;
1411 }
1412
1413 struct merge_simplify_state {
1414         struct commit *simplified;
1415 };
1416
1417 static struct merge_simplify_state *locate_simplify_state(struct rev_info *revs, struct commit *commit)
1418 {
1419         struct merge_simplify_state *st;
1420
1421         st = lookup_decoration(&revs->merge_simplification, &commit->object);
1422         if (!st) {
1423                 st = xcalloc(1, sizeof(*st));
1424                 add_decoration(&revs->merge_simplification, &commit->object, st);
1425         }
1426         return st;
1427 }
1428
1429 static struct commit_list **simplify_one(struct rev_info *revs, struct commit *commit, struct commit_list **tail)
1430 {
1431         struct commit_list *p;
1432         struct merge_simplify_state *st, *pst;
1433         int cnt;
1434
1435         st = locate_simplify_state(revs, commit);
1436
1437         /*
1438          * Have we handled this one?
1439          */
1440         if (st->simplified)
1441                 return tail;
1442
1443         /*
1444          * An UNINTERESTING commit simplifies to itself, so does a
1445          * root commit.  We do not rewrite parents of such commit
1446          * anyway.
1447          */
1448         if ((commit->object.flags & UNINTERESTING) || !commit->parents) {
1449                 st->simplified = commit;
1450                 return tail;
1451         }
1452
1453         /*
1454          * Do we know what commit all of our parents should be rewritten to?
1455          * Otherwise we are not ready to rewrite this one yet.
1456          */
1457         for (cnt = 0, p = commit->parents; p; p = p->next) {
1458                 pst = locate_simplify_state(revs, p->item);
1459                 if (!pst->simplified) {
1460                         tail = &commit_list_insert(p->item, tail)->next;
1461                         cnt++;
1462                 }
1463         }
1464         if (cnt) {
1465                 tail = &commit_list_insert(commit, tail)->next;
1466                 return tail;
1467         }
1468
1469         /*
1470          * Rewrite our list of parents.
1471          */
1472         for (p = commit->parents; p; p = p->next) {
1473                 pst = locate_simplify_state(revs, p->item);
1474                 p->item = pst->simplified;
1475         }
1476         cnt = remove_duplicate_parents(commit);
1477
1478         /*
1479          * It is possible that we are a merge and one side branch
1480          * does not have any commit that touches the given paths;
1481          * in such a case, the immediate parents will be rewritten
1482          * to different commits.
1483          *
1484          *      o----X          X: the commit we are looking at;
1485          *     /    /           o: a commit that touches the paths;
1486          * ---o----'
1487          *
1488          * Further reduce the parents by removing redundant parents.
1489          */
1490         if (1 < cnt) {
1491                 struct commit_list *h = reduce_heads(commit->parents);
1492                 cnt = commit_list_count(h);
1493                 free_commit_list(commit->parents);
1494                 commit->parents = h;
1495         }
1496
1497         /*
1498          * A commit simplifies to itself if it is a root, if it is
1499          * UNINTERESTING, if it touches the given paths, or if it is a
1500          * merge and its parents simplifies to more than one commits
1501          * (the first two cases are already handled at the beginning of
1502          * this function).
1503          *
1504          * Otherwise, it simplifies to what its sole parent simplifies to.
1505          */
1506         if (!cnt ||
1507             (commit->object.flags & UNINTERESTING) ||
1508             !(commit->object.flags & TREESAME) ||
1509             (1 < cnt))
1510                 st->simplified = commit;
1511         else {
1512                 pst = locate_simplify_state(revs, commit->parents->item);
1513                 st->simplified = pst->simplified;
1514         }
1515         return tail;
1516 }
1517
1518 static void simplify_merges(struct rev_info *revs)
1519 {
1520         struct commit_list *list;
1521         struct commit_list *yet_to_do, **tail;
1522
1523         if (!revs->topo_order)
1524                 sort_in_topological_order(&revs->commits, revs->lifo);
1525         if (!revs->prune)
1526                 return;
1527
1528         /* feed the list reversed */
1529         yet_to_do = NULL;
1530         for (list = revs->commits; list; list = list->next)
1531                 commit_list_insert(list->item, &yet_to_do);
1532         while (yet_to_do) {
1533                 list = yet_to_do;
1534                 yet_to_do = NULL;
1535                 tail = &yet_to_do;
1536                 while (list) {
1537                         struct commit *commit = list->item;
1538                         struct commit_list *next = list->next;
1539                         free(list);
1540                         list = next;
1541                         tail = simplify_one(revs, commit, tail);
1542                 }
1543         }
1544
1545         /* clean up the result, removing the simplified ones */
1546         list = revs->commits;
1547         revs->commits = NULL;
1548         tail = &revs->commits;
1549         while (list) {
1550                 struct commit *commit = list->item;
1551                 struct commit_list *next = list->next;
1552                 struct merge_simplify_state *st;
1553                 free(list);
1554                 list = next;
1555                 st = locate_simplify_state(revs, commit);
1556                 if (st->simplified == commit)
1557                         tail = &commit_list_insert(commit, tail)->next;
1558         }
1559 }
1560
1561 static void set_children(struct rev_info *revs)
1562 {
1563         struct commit_list *l;
1564         for (l = revs->commits; l; l = l->next) {
1565                 struct commit *commit = l->item;
1566                 struct commit_list *p;
1567
1568                 for (p = commit->parents; p; p = p->next)
1569                         add_child(revs, p->item, commit);
1570         }
1571 }
1572
1573 int prepare_revision_walk(struct rev_info *revs)
1574 {
1575         int nr = revs->pending.nr;
1576         struct object_array_entry *e, *list;
1577
1578         e = list = revs->pending.objects;
1579         revs->pending.nr = 0;
1580         revs->pending.alloc = 0;
1581         revs->pending.objects = NULL;
1582         while (--nr >= 0) {
1583                 struct commit *commit = handle_commit(revs, e->item, e->name);
1584                 if (commit) {
1585                         if (!(commit->object.flags & SEEN)) {
1586                                 commit->object.flags |= SEEN;
1587                                 insert_by_date(commit, &revs->commits);
1588                         }
1589                 }
1590                 e++;
1591         }
1592         free(list);
1593
1594         if (revs->no_walk)
1595                 return 0;
1596         if (revs->limited)
1597                 if (limit_list(revs) < 0)
1598                         return -1;
1599         if (revs->topo_order)
1600                 sort_in_topological_order(&revs->commits, revs->lifo);
1601         if (revs->simplify_merges)
1602                 simplify_merges(revs);
1603         if (revs->children.name)
1604                 set_children(revs);
1605         return 0;
1606 }
1607
1608 enum rewrite_result {
1609         rewrite_one_ok,
1610         rewrite_one_noparents,
1611         rewrite_one_error,
1612 };
1613
1614 static enum rewrite_result rewrite_one(struct rev_info *revs, struct commit **pp)
1615 {
1616         struct commit_list *cache = NULL;
1617
1618         for (;;) {
1619                 struct commit *p = *pp;
1620                 if (!revs->limited)
1621                         if (add_parents_to_list(revs, p, &revs->commits, &cache) < 0)
1622                                 return rewrite_one_error;
1623                 if (p->parents && p->parents->next)
1624                         return rewrite_one_ok;
1625                 if (p->object.flags & UNINTERESTING)
1626                         return rewrite_one_ok;
1627                 if (!(p->object.flags & TREESAME))
1628                         return rewrite_one_ok;
1629                 if (!p->parents)
1630                         return rewrite_one_noparents;
1631                 *pp = p->parents->item;
1632         }
1633 }
1634
1635 static int rewrite_parents(struct rev_info *revs, struct commit *commit)
1636 {
1637         struct commit_list **pp = &commit->parents;
1638         while (*pp) {
1639                 struct commit_list *parent = *pp;
1640                 switch (rewrite_one(revs, &parent->item)) {
1641                 case rewrite_one_ok:
1642                         break;
1643                 case rewrite_one_noparents:
1644                         *pp = parent->next;
1645                         continue;
1646                 case rewrite_one_error:
1647                         return -1;
1648                 }
1649                 pp = &parent->next;
1650         }
1651         remove_duplicate_parents(commit);
1652         return 0;
1653 }
1654
1655 static int commit_match(struct commit *commit, struct rev_info *opt)
1656 {
1657         if (!opt->grep_filter.pattern_list)
1658                 return 1;
1659         return grep_buffer(&opt->grep_filter,
1660                            NULL, /* we say nothing, not even filename */
1661                            commit->buffer, strlen(commit->buffer));
1662 }
1663
1664 static inline int want_ancestry(struct rev_info *revs)
1665 {
1666         return (revs->rewrite_parents || revs->children.name);
1667 }
1668
1669 enum commit_action get_commit_action(struct rev_info *revs, struct commit *commit)
1670 {
1671         if (commit->object.flags & SHOWN)
1672                 return commit_ignore;
1673         if (revs->unpacked && has_sha1_pack(commit->object.sha1))
1674                 return commit_ignore;
1675         if (revs->show_all)
1676                 return commit_show;
1677         if (commit->object.flags & UNINTERESTING)
1678                 return commit_ignore;
1679         if (revs->min_age != -1 && (commit->date > revs->min_age))
1680                 return commit_ignore;
1681         if (revs->no_merges && commit->parents && commit->parents->next)
1682                 return commit_ignore;
1683         if (revs->merges_only && !(commit->parents && commit->parents->next))
1684                 return commit_ignore;
1685         if (!commit_match(commit, revs))
1686                 return commit_ignore;
1687         if (revs->prune && revs->dense) {
1688                 /* Commit without changes? */
1689                 if (commit->object.flags & TREESAME) {
1690                         /* drop merges unless we want parenthood */
1691                         if (!want_ancestry(revs))
1692                                 return commit_ignore;
1693                         /* non-merge - always ignore it */
1694                         if (!commit->parents || !commit->parents->next)
1695                                 return commit_ignore;
1696                 }
1697         }
1698         return commit_show;
1699 }
1700
1701 enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit)
1702 {
1703         enum commit_action action = get_commit_action(revs, commit);
1704
1705         if (action == commit_show &&
1706             !revs->show_all &&
1707             revs->prune && revs->dense && want_ancestry(revs)) {
1708                 if (rewrite_parents(revs, commit) < 0)
1709                         return commit_error;
1710         }
1711         return action;
1712 }
1713
1714 static struct commit *get_revision_1(struct rev_info *revs)
1715 {
1716         if (!revs->commits)
1717                 return NULL;
1718
1719         do {
1720                 struct commit_list *entry = revs->commits;
1721                 struct commit *commit = entry->item;
1722
1723                 revs->commits = entry->next;
1724                 free(entry);
1725
1726                 if (revs->reflog_info)
1727                         fake_reflog_parent(revs->reflog_info, commit);
1728
1729                 /*
1730                  * If we haven't done the list limiting, we need to look at
1731                  * the parents here. We also need to do the date-based limiting
1732                  * that we'd otherwise have done in limit_list().
1733                  */
1734                 if (!revs->limited) {
1735                         if (revs->max_age != -1 &&
1736                             (commit->date < revs->max_age))
1737                                 continue;
1738                         if (add_parents_to_list(revs, commit, &revs->commits, NULL) < 0)
1739                                 die("Failed to traverse parents of commit %s",
1740                                     sha1_to_hex(commit->object.sha1));
1741                 }
1742
1743                 switch (simplify_commit(revs, commit)) {
1744                 case commit_ignore:
1745                         continue;
1746                 case commit_error:
1747                         die("Failed to simplify parents of commit %s",
1748                             sha1_to_hex(commit->object.sha1));
1749                 default:
1750                         return commit;
1751                 }
1752         } while (revs->commits);
1753         return NULL;
1754 }
1755
1756 static void gc_boundary(struct object_array *array)
1757 {
1758         unsigned nr = array->nr;
1759         unsigned alloc = array->alloc;
1760         struct object_array_entry *objects = array->objects;
1761
1762         if (alloc <= nr) {
1763                 unsigned i, j;
1764                 for (i = j = 0; i < nr; i++) {
1765                         if (objects[i].item->flags & SHOWN)
1766                                 continue;
1767                         if (i != j)
1768                                 objects[j] = objects[i];
1769                         j++;
1770                 }
1771                 for (i = j; i < nr; i++)
1772                         objects[i].item = NULL;
1773                 array->nr = j;
1774         }
1775 }
1776
1777 static void create_boundary_commit_list(struct rev_info *revs)
1778 {
1779         unsigned i;
1780         struct commit *c;
1781         struct object_array *array = &revs->boundary_commits;
1782         struct object_array_entry *objects = array->objects;
1783
1784         /*
1785          * If revs->commits is non-NULL at this point, an error occurred in
1786          * get_revision_1().  Ignore the error and continue printing the
1787          * boundary commits anyway.  (This is what the code has always
1788          * done.)
1789          */
1790         if (revs->commits) {
1791                 free_commit_list(revs->commits);
1792                 revs->commits = NULL;
1793         }
1794
1795         /*
1796          * Put all of the actual boundary commits from revs->boundary_commits
1797          * into revs->commits
1798          */
1799         for (i = 0; i < array->nr; i++) {
1800                 c = (struct commit *)(objects[i].item);
1801                 if (!c)
1802                         continue;
1803                 if (!(c->object.flags & CHILD_SHOWN))
1804                         continue;
1805                 if (c->object.flags & (SHOWN | BOUNDARY))
1806                         continue;
1807                 c->object.flags |= BOUNDARY;
1808                 commit_list_insert(c, &revs->commits);
1809         }
1810
1811         /*
1812          * If revs->topo_order is set, sort the boundary commits
1813          * in topological order
1814          */
1815         sort_in_topological_order(&revs->commits, revs->lifo);
1816 }
1817
1818 static struct commit *get_revision_internal(struct rev_info *revs)
1819 {
1820         struct commit *c = NULL;
1821         struct commit_list *l;
1822
1823         if (revs->boundary == 2) {
1824                 /*
1825                  * All of the normal commits have already been returned,
1826                  * and we are now returning boundary commits.
1827                  * create_boundary_commit_list() has populated
1828                  * revs->commits with the remaining commits to return.
1829                  */
1830                 c = pop_commit(&revs->commits);
1831                 if (c)
1832                         c->object.flags |= SHOWN;
1833                 return c;
1834         }
1835
1836         /*
1837          * Now pick up what they want to give us
1838          */
1839         c = get_revision_1(revs);
1840         if (c) {
1841                 while (0 < revs->skip_count) {
1842                         revs->skip_count--;
1843                         c = get_revision_1(revs);
1844                         if (!c)
1845                                 break;
1846                 }
1847         }
1848
1849         /*
1850          * Check the max_count.
1851          */
1852         switch (revs->max_count) {
1853         case -1:
1854                 break;
1855         case 0:
1856                 c = NULL;
1857                 break;
1858         default:
1859                 revs->max_count--;
1860         }
1861
1862         if (c)
1863                 c->object.flags |= SHOWN;
1864
1865         if (!revs->boundary) {
1866                 return c;
1867         }
1868
1869         if (!c) {
1870                 /*
1871                  * get_revision_1() runs out the commits, and
1872                  * we are done computing the boundaries.
1873                  * switch to boundary commits output mode.
1874                  */
1875                 revs->boundary = 2;
1876
1877                 /*
1878                  * Update revs->commits to contain the list of
1879                  * boundary commits.
1880                  */
1881                 create_boundary_commit_list(revs);
1882
1883                 return get_revision_internal(revs);
1884         }
1885
1886         /*
1887          * boundary commits are the commits that are parents of the
1888          * ones we got from get_revision_1() but they themselves are
1889          * not returned from get_revision_1().  Before returning
1890          * 'c', we need to mark its parents that they could be boundaries.
1891          */
1892
1893         for (l = c->parents; l; l = l->next) {
1894                 struct object *p;
1895                 p = &(l->item->object);
1896                 if (p->flags & (CHILD_SHOWN | SHOWN))
1897                         continue;
1898                 p->flags |= CHILD_SHOWN;
1899                 gc_boundary(&revs->boundary_commits);
1900                 add_object_array(p, NULL, &revs->boundary_commits);
1901         }
1902
1903         return c;
1904 }
1905
1906 struct commit *get_revision(struct rev_info *revs)
1907 {
1908         struct commit *c;
1909         struct commit_list *reversed;
1910
1911         if (revs->reverse) {
1912                 reversed = NULL;
1913                 while ((c = get_revision_internal(revs))) {
1914                         commit_list_insert(c, &reversed);
1915                 }
1916                 revs->commits = reversed;
1917                 revs->reverse = 0;
1918                 revs->reverse_output_stage = 1;
1919         }
1920
1921         if (revs->reverse_output_stage)
1922                 return pop_commit(&revs->commits);
1923
1924         c = get_revision_internal(revs);
1925         if (c && revs->graph)
1926                 graph_update(revs->graph, c);
1927         return c;
1928 }