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