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