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