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