Imported Upstream version 2.15.4
[platform/upstream/git.git] / tree-walk.c
1 #include "cache.h"
2 #include "tree-walk.h"
3 #include "unpack-trees.h"
4 #include "dir.h"
5 #include "tree.h"
6 #include "pathspec.h"
7
8 static const char *get_mode(const char *str, unsigned int *modep)
9 {
10         unsigned char c;
11         unsigned int mode = 0;
12
13         if (*str == ' ')
14                 return NULL;
15
16         while ((c = *str++) != ' ') {
17                 if (c < '0' || c > '7')
18                         return NULL;
19                 mode = (mode << 3) + (c - '0');
20         }
21         *modep = mode;
22         return str;
23 }
24
25 static int decode_tree_entry(struct tree_desc *desc, const char *buf, unsigned long size, struct strbuf *err)
26 {
27         const char *path;
28         unsigned int mode, len;
29
30         if (size < 23 || buf[size - 21]) {
31                 strbuf_addstr(err, _("too-short tree object"));
32                 return -1;
33         }
34
35         path = get_mode(buf, &mode);
36         if (!path) {
37                 strbuf_addstr(err, _("malformed mode in tree entry"));
38                 return -1;
39         }
40         if (!*path) {
41                 strbuf_addstr(err, _("empty filename in tree entry"));
42                 return -1;
43         }
44 #ifdef GIT_WINDOWS_NATIVE
45         if (protect_ntfs && strchr(path, '\\')) {
46                 strbuf_addf(err, _("filename in tree entry contains backslash: '%s'"), path);
47                 return -1;
48         }
49 #endif
50         len = strlen(path) + 1;
51
52         /* Initialize the descriptor entry */
53         desc->entry.path = path;
54         desc->entry.mode = canon_mode(mode);
55         desc->entry.oid  = (const struct object_id *)(path + len);
56
57         return 0;
58 }
59
60 static int init_tree_desc_internal(struct tree_desc *desc, const void *buffer, unsigned long size, struct strbuf *err)
61 {
62         desc->buffer = buffer;
63         desc->size = size;
64         if (size)
65                 return decode_tree_entry(desc, buffer, size, err);
66         return 0;
67 }
68
69 void init_tree_desc(struct tree_desc *desc, const void *buffer, unsigned long size)
70 {
71         struct strbuf err = STRBUF_INIT;
72         if (init_tree_desc_internal(desc, buffer, size, &err))
73                 die("%s", err.buf);
74         strbuf_release(&err);
75 }
76
77 int init_tree_desc_gently(struct tree_desc *desc, const void *buffer, unsigned long size)
78 {
79         struct strbuf err = STRBUF_INIT;
80         int result = init_tree_desc_internal(desc, buffer, size, &err);
81         if (result)
82                 error("%s", err.buf);
83         strbuf_release(&err);
84         return result;
85 }
86
87 void *fill_tree_descriptor(struct tree_desc *desc, const struct object_id *oid)
88 {
89         unsigned long size = 0;
90         void *buf = NULL;
91
92         if (oid) {
93                 buf = read_object_with_reference(oid->hash, tree_type, &size,
94                                                  NULL);
95                 if (!buf)
96                         die("unable to read tree %s", oid_to_hex(oid));
97         }
98         init_tree_desc(desc, buf, size);
99         return buf;
100 }
101
102 static void entry_clear(struct name_entry *a)
103 {
104         memset(a, 0, sizeof(*a));
105 }
106
107 static void entry_extract(struct tree_desc *t, struct name_entry *a)
108 {
109         *a = t->entry;
110 }
111
112 static int update_tree_entry_internal(struct tree_desc *desc, struct strbuf *err)
113 {
114         const void *buf = desc->buffer;
115         const unsigned char *end = desc->entry.oid->hash + 20;
116         unsigned long size = desc->size;
117         unsigned long len = end - (const unsigned char *)buf;
118
119         if (size < len)
120                 die(_("too-short tree file"));
121         buf = end;
122         size -= len;
123         desc->buffer = buf;
124         desc->size = size;
125         if (size)
126                 return decode_tree_entry(desc, buf, size, err);
127         return 0;
128 }
129
130 void update_tree_entry(struct tree_desc *desc)
131 {
132         struct strbuf err = STRBUF_INIT;
133         if (update_tree_entry_internal(desc, &err))
134                 die("%s", err.buf);
135         strbuf_release(&err);
136 }
137
138 int update_tree_entry_gently(struct tree_desc *desc)
139 {
140         struct strbuf err = STRBUF_INIT;
141         if (update_tree_entry_internal(desc, &err)) {
142                 error("%s", err.buf);
143                 strbuf_release(&err);
144                 /* Stop processing this tree after error */
145                 desc->size = 0;
146                 return -1;
147         }
148         strbuf_release(&err);
149         return 0;
150 }
151
152 int tree_entry(struct tree_desc *desc, struct name_entry *entry)
153 {
154         if (!desc->size)
155                 return 0;
156
157         *entry = desc->entry;
158         update_tree_entry(desc);
159         return 1;
160 }
161
162 int tree_entry_gently(struct tree_desc *desc, struct name_entry *entry)
163 {
164         if (!desc->size)
165                 return 0;
166
167         *entry = desc->entry;
168         if (update_tree_entry_gently(desc))
169                 return 0;
170         return 1;
171 }
172
173 void setup_traverse_info(struct traverse_info *info, const char *base)
174 {
175         int pathlen = strlen(base);
176         static struct traverse_info dummy;
177
178         memset(info, 0, sizeof(*info));
179         if (pathlen && base[pathlen-1] == '/')
180                 pathlen--;
181         info->pathlen = pathlen ? pathlen + 1 : 0;
182         info->name.path = base;
183         info->name.oid = (void *)(base + pathlen + 1);
184         if (pathlen)
185                 info->prev = &dummy;
186 }
187
188 char *make_traverse_path(char *path, const struct traverse_info *info, const struct name_entry *n)
189 {
190         int len = tree_entry_len(n);
191         int pathlen = info->pathlen;
192
193         path[pathlen + len] = 0;
194         for (;;) {
195                 memcpy(path + pathlen, n->path, len);
196                 if (!pathlen)
197                         break;
198                 path[--pathlen] = '/';
199                 n = &info->name;
200                 len = tree_entry_len(n);
201                 info = info->prev;
202                 pathlen -= len;
203         }
204         return path;
205 }
206
207 struct tree_desc_skip {
208         struct tree_desc_skip *prev;
209         const void *ptr;
210 };
211
212 struct tree_desc_x {
213         struct tree_desc d;
214         struct tree_desc_skip *skip;
215 };
216
217 static int check_entry_match(const char *a, int a_len, const char *b, int b_len)
218 {
219         /*
220          * The caller wants to pick *a* from a tree or nothing.
221          * We are looking at *b* in a tree.
222          *
223          * (0) If a and b are the same name, we are trivially happy.
224          *
225          * There are three possibilities where *a* could be hiding
226          * behind *b*.
227          *
228          * (1) *a* == "t",   *b* == "ab"  i.e. *b* sorts earlier than *a* no
229          *                                matter what.
230          * (2) *a* == "t",   *b* == "t-2" and "t" is a subtree in the tree;
231          * (3) *a* == "t-2", *b* == "t"   and "t-2" is a blob in the tree.
232          *
233          * Otherwise we know *a* won't appear in the tree without
234          * scanning further.
235          */
236
237         int cmp = name_compare(a, a_len, b, b_len);
238
239         /* Most common case first -- reading sync'd trees */
240         if (!cmp)
241                 return cmp;
242
243         if (0 < cmp) {
244                 /* a comes after b; it does not matter if it is case (3)
245                 if (b_len < a_len && !memcmp(a, b, b_len) && a[b_len] < '/')
246                         return 1;
247                 */
248                 return 1; /* keep looking */
249         }
250
251         /* b comes after a; are we looking at case (2)? */
252         if (a_len < b_len && !memcmp(a, b, a_len) && b[a_len] < '/')
253                 return 1; /* keep looking */
254
255         return -1; /* a cannot appear in the tree */
256 }
257
258 /*
259  * From the extended tree_desc, extract the first name entry, while
260  * paying attention to the candidate "first" name.  Most importantly,
261  * when looking for an entry, if there are entries that sorts earlier
262  * in the tree object representation than that name, skip them and
263  * process the named entry first.  We will remember that we haven't
264  * processed the first entry yet, and in the later call skip the
265  * entry we processed early when update_extended_entry() is called.
266  *
267  * E.g. if the underlying tree object has these entries:
268  *
269  *    blob    "t-1"
270  *    blob    "t-2"
271  *    tree    "t"
272  *    blob    "t=1"
273  *
274  * and the "first" asks for "t", remember that we still need to
275  * process "t-1" and "t-2" but extract "t".  After processing the
276  * entry "t" from this call, the caller will let us know by calling
277  * update_extended_entry() that we can remember "t" has been processed
278  * already.
279  */
280
281 static void extended_entry_extract(struct tree_desc_x *t,
282                                    struct name_entry *a,
283                                    const char *first,
284                                    int first_len)
285 {
286         const char *path;
287         int len;
288         struct tree_desc probe;
289         struct tree_desc_skip *skip;
290
291         /*
292          * Extract the first entry from the tree_desc, but skip the
293          * ones that we already returned in earlier rounds.
294          */
295         while (1) {
296                 if (!t->d.size) {
297                         entry_clear(a);
298                         break; /* not found */
299                 }
300                 entry_extract(&t->d, a);
301                 for (skip = t->skip; skip; skip = skip->prev)
302                         if (a->path == skip->ptr)
303                                 break; /* found */
304                 if (!skip)
305                         break;
306                 /* We have processed this entry already. */
307                 update_tree_entry(&t->d);
308         }
309
310         if (!first || !a->path)
311                 return;
312
313         /*
314          * The caller wants "first" from this tree, or nothing.
315          */
316         path = a->path;
317         len = tree_entry_len(a);
318         switch (check_entry_match(first, first_len, path, len)) {
319         case -1:
320                 entry_clear(a);
321         case 0:
322                 return;
323         default:
324                 break;
325         }
326
327         /*
328          * We need to look-ahead -- we suspect that a subtree whose
329          * name is "first" may be hiding behind the current entry "path".
330          */
331         probe = t->d;
332         while (probe.size) {
333                 entry_extract(&probe, a);
334                 path = a->path;
335                 len = tree_entry_len(a);
336                 switch (check_entry_match(first, first_len, path, len)) {
337                 case -1:
338                         entry_clear(a);
339                 case 0:
340                         return;
341                 default:
342                         update_tree_entry(&probe);
343                         break;
344                 }
345                 /* keep looking */
346         }
347         entry_clear(a);
348 }
349
350 static void update_extended_entry(struct tree_desc_x *t, struct name_entry *a)
351 {
352         if (t->d.entry.path == a->path) {
353                 update_tree_entry(&t->d);
354         } else {
355                 /* we have returned this entry early */
356                 struct tree_desc_skip *skip = xmalloc(sizeof(*skip));
357                 skip->ptr = a->path;
358                 skip->prev = t->skip;
359                 t->skip = skip;
360         }
361 }
362
363 static void free_extended_entry(struct tree_desc_x *t)
364 {
365         struct tree_desc_skip *p, *s;
366
367         for (s = t->skip; s; s = p) {
368                 p = s->prev;
369                 free(s);
370         }
371 }
372
373 static inline int prune_traversal(struct name_entry *e,
374                                   struct traverse_info *info,
375                                   struct strbuf *base,
376                                   int still_interesting)
377 {
378         if (!info->pathspec || still_interesting == 2)
379                 return 2;
380         if (still_interesting < 0)
381                 return still_interesting;
382         return tree_entry_interesting(e, base, 0, info->pathspec);
383 }
384
385 int traverse_trees(int n, struct tree_desc *t, struct traverse_info *info)
386 {
387         int error = 0;
388         struct name_entry *entry = xmalloc(n*sizeof(*entry));
389         int i;
390         struct tree_desc_x *tx = xcalloc(n, sizeof(*tx));
391         struct strbuf base = STRBUF_INIT;
392         int interesting = 1;
393         char *traverse_path;
394
395         for (i = 0; i < n; i++)
396                 tx[i].d = t[i];
397
398         if (info->prev) {
399                 strbuf_grow(&base, info->pathlen);
400                 make_traverse_path(base.buf, info->prev, &info->name);
401                 base.buf[info->pathlen-1] = '/';
402                 strbuf_setlen(&base, info->pathlen);
403                 traverse_path = xstrndup(base.buf, info->pathlen);
404         } else {
405                 traverse_path = xstrndup(info->name.path, info->pathlen);
406         }
407         info->traverse_path = traverse_path;
408         for (;;) {
409                 int trees_used;
410                 unsigned long mask, dirmask;
411                 const char *first = NULL;
412                 int first_len = 0;
413                 struct name_entry *e = NULL;
414                 int len;
415
416                 for (i = 0; i < n; i++) {
417                         e = entry + i;
418                         extended_entry_extract(tx + i, e, NULL, 0);
419                 }
420
421                 /*
422                  * A tree may have "t-2" at the current location even
423                  * though it may have "t" that is a subtree behind it,
424                  * and another tree may return "t".  We want to grab
425                  * all "t" from all trees to match in such a case.
426                  */
427                 for (i = 0; i < n; i++) {
428                         e = entry + i;
429                         if (!e->path)
430                                 continue;
431                         len = tree_entry_len(e);
432                         if (!first) {
433                                 first = e->path;
434                                 first_len = len;
435                                 continue;
436                         }
437                         if (name_compare(e->path, len, first, first_len) < 0) {
438                                 first = e->path;
439                                 first_len = len;
440                         }
441                 }
442
443                 if (first) {
444                         for (i = 0; i < n; i++) {
445                                 e = entry + i;
446                                 extended_entry_extract(tx + i, e, first, first_len);
447                                 /* Cull the ones that are not the earliest */
448                                 if (!e->path)
449                                         continue;
450                                 len = tree_entry_len(e);
451                                 if (name_compare(e->path, len, first, first_len))
452                                         entry_clear(e);
453                         }
454                 }
455
456                 /* Now we have in entry[i] the earliest name from the trees */
457                 mask = 0;
458                 dirmask = 0;
459                 for (i = 0; i < n; i++) {
460                         if (!entry[i].path)
461                                 continue;
462                         mask |= 1ul << i;
463                         if (S_ISDIR(entry[i].mode))
464                                 dirmask |= 1ul << i;
465                         e = &entry[i];
466                 }
467                 if (!mask)
468                         break;
469                 interesting = prune_traversal(e, info, &base, interesting);
470                 if (interesting < 0)
471                         break;
472                 if (interesting) {
473                         trees_used = info->fn(n, mask, dirmask, entry, info);
474                         if (trees_used < 0) {
475                                 error = trees_used;
476                                 if (!info->show_all_errors)
477                                         break;
478                         }
479                         mask &= trees_used;
480                 }
481                 for (i = 0; i < n; i++)
482                         if (mask & (1ul << i))
483                                 update_extended_entry(tx + i, entry + i);
484         }
485         free(entry);
486         for (i = 0; i < n; i++)
487                 free_extended_entry(tx + i);
488         free(tx);
489         free(traverse_path);
490         info->traverse_path = NULL;
491         strbuf_release(&base);
492         return error;
493 }
494
495 struct dir_state {
496         void *tree;
497         unsigned long size;
498         unsigned char sha1[20];
499 };
500
501 static int find_tree_entry(struct tree_desc *t, const char *name, unsigned char *result, unsigned *mode)
502 {
503         int namelen = strlen(name);
504         while (t->size) {
505                 const char *entry;
506                 const struct object_id *oid;
507                 int entrylen, cmp;
508
509                 oid = tree_entry_extract(t, &entry, mode);
510                 entrylen = tree_entry_len(&t->entry);
511                 update_tree_entry(t);
512                 if (entrylen > namelen)
513                         continue;
514                 cmp = memcmp(name, entry, entrylen);
515                 if (cmp > 0)
516                         continue;
517                 if (cmp < 0)
518                         break;
519                 if (entrylen == namelen) {
520                         hashcpy(result, oid->hash);
521                         return 0;
522                 }
523                 if (name[entrylen] != '/')
524                         continue;
525                 if (!S_ISDIR(*mode))
526                         break;
527                 if (++entrylen == namelen) {
528                         hashcpy(result, oid->hash);
529                         return 0;
530                 }
531                 return get_tree_entry(oid->hash, name + entrylen, result, mode);
532         }
533         return -1;
534 }
535
536 int get_tree_entry(const unsigned char *tree_sha1, const char *name, unsigned char *sha1, unsigned *mode)
537 {
538         int retval;
539         void *tree;
540         unsigned long size;
541         unsigned char root[20];
542
543         tree = read_object_with_reference(tree_sha1, tree_type, &size, root);
544         if (!tree)
545                 return -1;
546
547         if (name[0] == '\0') {
548                 hashcpy(sha1, root);
549                 free(tree);
550                 return 0;
551         }
552
553         if (!size) {
554                 retval = -1;
555         } else {
556                 struct tree_desc t;
557                 init_tree_desc(&t, tree, size);
558                 retval = find_tree_entry(&t, name, sha1, mode);
559         }
560         free(tree);
561         return retval;
562 }
563
564 /*
565  * This is Linux's built-in max for the number of symlinks to follow.
566  * That limit, of course, does not affect git, but it's a reasonable
567  * choice.
568  */
569 #define GET_TREE_ENTRY_FOLLOW_SYMLINKS_MAX_LINKS 40
570
571 /**
572  * Find a tree entry by following symlinks in tree_sha (which is
573  * assumed to be the root of the repository).  In the event that a
574  * symlink points outside the repository (e.g. a link to /foo or a
575  * root-level link to ../foo), the portion of the link which is
576  * outside the repository will be returned in result_path, and *mode
577  * will be set to 0.  It is assumed that result_path is uninitialized.
578  * If there are no symlinks, or the end result of the symlink chain
579  * points to an object inside the repository, result will be filled in
580  * with the sha1 of the found object, and *mode will hold the mode of
581  * the object.
582  *
583  * See the code for enum follow_symlink_result for a description of
584  * the return values.
585  */
586 enum follow_symlinks_result get_tree_entry_follow_symlinks(unsigned char *tree_sha1, const char *name, unsigned char *result, struct strbuf *result_path, unsigned *mode)
587 {
588         int retval = MISSING_OBJECT;
589         struct dir_state *parents = NULL;
590         size_t parents_alloc = 0;
591         size_t i, parents_nr = 0;
592         unsigned char current_tree_sha1[20];
593         struct strbuf namebuf = STRBUF_INIT;
594         struct tree_desc t;
595         int follows_remaining = GET_TREE_ENTRY_FOLLOW_SYMLINKS_MAX_LINKS;
596
597         init_tree_desc(&t, NULL, 0UL);
598         strbuf_addstr(&namebuf, name);
599         hashcpy(current_tree_sha1, tree_sha1);
600
601         while (1) {
602                 int find_result;
603                 char *first_slash;
604                 char *remainder = NULL;
605
606                 if (!t.buffer) {
607                         void *tree;
608                         unsigned char root[20];
609                         unsigned long size;
610                         tree = read_object_with_reference(current_tree_sha1,
611                                                           tree_type, &size,
612                                                           root);
613                         if (!tree)
614                                 goto done;
615
616                         ALLOC_GROW(parents, parents_nr + 1, parents_alloc);
617                         parents[parents_nr].tree = tree;
618                         parents[parents_nr].size = size;
619                         hashcpy(parents[parents_nr].sha1, root);
620                         parents_nr++;
621
622                         if (namebuf.buf[0] == '\0') {
623                                 hashcpy(result, root);
624                                 retval = FOUND;
625                                 goto done;
626                         }
627
628                         if (!size)
629                                 goto done;
630
631                         /* descend */
632                         init_tree_desc(&t, tree, size);
633                 }
634
635                 /* Handle symlinks to e.g. a//b by removing leading slashes */
636                 while (namebuf.buf[0] == '/') {
637                         strbuf_remove(&namebuf, 0, 1);
638                 }
639
640                 /* Split namebuf into a first component and a remainder */
641                 if ((first_slash = strchr(namebuf.buf, '/'))) {
642                         *first_slash = 0;
643                         remainder = first_slash + 1;
644                 }
645
646                 if (!strcmp(namebuf.buf, "..")) {
647                         struct dir_state *parent;
648                         /*
649                          * We could end up with .. in the namebuf if it
650                          * appears in a symlink.
651                          */
652
653                         if (parents_nr == 1) {
654                                 if (remainder)
655                                         *first_slash = '/';
656                                 strbuf_add(result_path, namebuf.buf,
657                                            namebuf.len);
658                                 *mode = 0;
659                                 retval = FOUND;
660                                 goto done;
661                         }
662                         parent = &parents[parents_nr - 1];
663                         free(parent->tree);
664                         parents_nr--;
665                         parent = &parents[parents_nr - 1];
666                         init_tree_desc(&t, parent->tree, parent->size);
667                         strbuf_remove(&namebuf, 0, remainder ? 3 : 2);
668                         continue;
669                 }
670
671                 /* We could end up here via a symlink to dir/.. */
672                 if (namebuf.buf[0] == '\0') {
673                         hashcpy(result, parents[parents_nr - 1].sha1);
674                         retval = FOUND;
675                         goto done;
676                 }
677
678                 /* Look up the first (or only) path component in the tree. */
679                 find_result = find_tree_entry(&t, namebuf.buf,
680                                               current_tree_sha1, mode);
681                 if (find_result) {
682                         goto done;
683                 }
684
685                 if (S_ISDIR(*mode)) {
686                         if (!remainder) {
687                                 hashcpy(result, current_tree_sha1);
688                                 retval = FOUND;
689                                 goto done;
690                         }
691                         /* Descend the tree */
692                         t.buffer = NULL;
693                         strbuf_remove(&namebuf, 0,
694                                       1 + first_slash - namebuf.buf);
695                 } else if (S_ISREG(*mode)) {
696                         if (!remainder) {
697                                 hashcpy(result, current_tree_sha1);
698                                 retval = FOUND;
699                         } else {
700                                 retval = NOT_DIR;
701                         }
702                         goto done;
703                 } else if (S_ISLNK(*mode)) {
704                         /* Follow a symlink */
705                         unsigned long link_len;
706                         size_t len;
707                         char *contents, *contents_start;
708                         struct dir_state *parent;
709                         enum object_type type;
710
711                         if (follows_remaining-- == 0) {
712                                 /* Too many symlinks followed */
713                                 retval = SYMLINK_LOOP;
714                                 goto done;
715                         }
716
717                         /*
718                          * At this point, we have followed at a least
719                          * one symlink, so on error we need to report this.
720                          */
721                         retval = DANGLING_SYMLINK;
722
723                         contents = read_sha1_file(current_tree_sha1, &type,
724                                                   &link_len);
725
726                         if (!contents)
727                                 goto done;
728
729                         if (contents[0] == '/') {
730                                 strbuf_addstr(result_path, contents);
731                                 free(contents);
732                                 *mode = 0;
733                                 retval = FOUND;
734                                 goto done;
735                         }
736
737                         if (remainder)
738                                 len = first_slash - namebuf.buf;
739                         else
740                                 len = namebuf.len;
741
742                         contents_start = contents;
743
744                         parent = &parents[parents_nr - 1];
745                         init_tree_desc(&t, parent->tree, parent->size);
746                         strbuf_splice(&namebuf, 0, len,
747                                       contents_start, link_len);
748                         if (remainder)
749                                 namebuf.buf[link_len] = '/';
750                         free(contents);
751                 }
752         }
753 done:
754         for (i = 0; i < parents_nr; i++)
755                 free(parents[i].tree);
756         free(parents);
757
758         strbuf_release(&namebuf);
759         return retval;
760 }
761
762 static int match_entry(const struct pathspec_item *item,
763                        const struct name_entry *entry, int pathlen,
764                        const char *match, int matchlen,
765                        enum interesting *never_interesting)
766 {
767         int m = -1; /* signals that we haven't called strncmp() */
768
769         if (item->magic & PATHSPEC_ICASE)
770                 /*
771                  * "Never interesting" trick requires exact
772                  * matching. We could do something clever with inexact
773                  * matching, but it's trickier (and not to forget that
774                  * strcasecmp is locale-dependent, at least in
775                  * glibc). Just disable it for now. It can't be worse
776                  * than the wildcard's codepath of '[Tt][Hi][Is][Ss]'
777                  * pattern.
778                  */
779                 *never_interesting = entry_not_interesting;
780         else if (*never_interesting != entry_not_interesting) {
781                 /*
782                  * We have not seen any match that sorts later
783                  * than the current path.
784                  */
785
786                 /*
787                  * Does match sort strictly earlier than path
788                  * with their common parts?
789                  */
790                 m = strncmp(match, entry->path,
791                             (matchlen < pathlen) ? matchlen : pathlen);
792                 if (m < 0)
793                         return 0;
794
795                 /*
796                  * If we come here even once, that means there is at
797                  * least one pathspec that would sort equal to or
798                  * later than the path we are currently looking at.
799                  * In other words, if we have never reached this point
800                  * after iterating all pathspecs, it means all
801                  * pathspecs are either outside of base, or inside the
802                  * base but sorts strictly earlier than the current
803                  * one.  In either case, they will never match the
804                  * subsequent entries.  In such a case, we initialized
805                  * the variable to -1 and that is what will be
806                  * returned, allowing the caller to terminate early.
807                  */
808                 *never_interesting = entry_not_interesting;
809         }
810
811         if (pathlen > matchlen)
812                 return 0;
813
814         if (matchlen > pathlen) {
815                 if (match[pathlen] != '/')
816                         return 0;
817                 if (!S_ISDIR(entry->mode) && !S_ISGITLINK(entry->mode))
818                         return 0;
819         }
820
821         if (m == -1)
822                 /*
823                  * we cheated and did not do strncmp(), so we do
824                  * that here.
825                  */
826                 m = ps_strncmp(item, match, entry->path, pathlen);
827
828         /*
829          * If common part matched earlier then it is a hit,
830          * because we rejected the case where path is not a
831          * leading directory and is shorter than match.
832          */
833         if (!m)
834                 /*
835                  * match_entry does not check if the prefix part is
836                  * matched case-sensitively. If the entry is a
837                  * directory and part of prefix, it'll be rematched
838                  * eventually by basecmp with special treatment for
839                  * the prefix.
840                  */
841                 return 1;
842
843         return 0;
844 }
845
846 /* :(icase)-aware string compare */
847 static int basecmp(const struct pathspec_item *item,
848                    const char *base, const char *match, int len)
849 {
850         if (item->magic & PATHSPEC_ICASE) {
851                 int ret, n = len > item->prefix ? item->prefix : len;
852                 ret = strncmp(base, match, n);
853                 if (ret)
854                         return ret;
855                 base += n;
856                 match += n;
857                 len -= n;
858         }
859         return ps_strncmp(item, base, match, len);
860 }
861
862 static int match_dir_prefix(const struct pathspec_item *item,
863                             const char *base,
864                             const char *match, int matchlen)
865 {
866         if (basecmp(item, base, match, matchlen))
867                 return 0;
868
869         /*
870          * If the base is a subdirectory of a path which
871          * was specified, all of them are interesting.
872          */
873         if (!matchlen ||
874             base[matchlen] == '/' ||
875             match[matchlen - 1] == '/')
876                 return 1;
877
878         /* Just a random prefix match */
879         return 0;
880 }
881
882 /*
883  * Perform matching on the leading non-wildcard part of
884  * pathspec. item->nowildcard_len must be greater than zero. Return
885  * non-zero if base is matched.
886  */
887 static int match_wildcard_base(const struct pathspec_item *item,
888                                const char *base, int baselen,
889                                int *matched)
890 {
891         const char *match = item->match;
892         /* the wildcard part is not considered in this function */
893         int matchlen = item->nowildcard_len;
894
895         if (baselen) {
896                 int dirlen;
897                 /*
898                  * Return early if base is longer than the
899                  * non-wildcard part but it does not match.
900                  */
901                 if (baselen >= matchlen) {
902                         *matched = matchlen;
903                         return !basecmp(item, base, match, matchlen);
904                 }
905
906                 dirlen = matchlen;
907                 while (dirlen && match[dirlen - 1] != '/')
908                         dirlen--;
909
910                 /*
911                  * Return early if base is shorter than the
912                  * non-wildcard part but it does not match. Note that
913                  * base ends with '/' so we are sure it really matches
914                  * directory
915                  */
916                 if (basecmp(item, base, match, baselen))
917                         return 0;
918                 *matched = baselen;
919         } else
920                 *matched = 0;
921         /*
922          * we could have checked entry against the non-wildcard part
923          * that is not in base and does similar never_interesting
924          * optimization as in match_entry. For now just be happy with
925          * base comparison.
926          */
927         return entry_interesting;
928 }
929
930 /*
931  * Is a tree entry interesting given the pathspec we have?
932  *
933  * Pre-condition: either baselen == base_offset (i.e. empty path)
934  * or base[baselen-1] == '/' (i.e. with trailing slash).
935  */
936 static enum interesting do_match(const struct name_entry *entry,
937                                  struct strbuf *base, int base_offset,
938                                  const struct pathspec *ps,
939                                  int exclude)
940 {
941         int i;
942         int pathlen, baselen = base->len - base_offset;
943         enum interesting never_interesting = ps->has_wildcard ?
944                 entry_not_interesting : all_entries_not_interesting;
945
946         GUARD_PATHSPEC(ps,
947                        PATHSPEC_FROMTOP |
948                        PATHSPEC_MAXDEPTH |
949                        PATHSPEC_LITERAL |
950                        PATHSPEC_GLOB |
951                        PATHSPEC_ICASE |
952                        PATHSPEC_EXCLUDE);
953
954         if (!ps->nr) {
955                 if (!ps->recursive ||
956                     !(ps->magic & PATHSPEC_MAXDEPTH) ||
957                     ps->max_depth == -1)
958                         return all_entries_interesting;
959                 return within_depth(base->buf + base_offset, baselen,
960                                     !!S_ISDIR(entry->mode),
961                                     ps->max_depth) ?
962                         entry_interesting : entry_not_interesting;
963         }
964
965         pathlen = tree_entry_len(entry);
966
967         for (i = ps->nr - 1; i >= 0; i--) {
968                 const struct pathspec_item *item = ps->items+i;
969                 const char *match = item->match;
970                 const char *base_str = base->buf + base_offset;
971                 int matchlen = item->len, matched = 0;
972
973                 if ((!exclude &&   item->magic & PATHSPEC_EXCLUDE) ||
974                     ( exclude && !(item->magic & PATHSPEC_EXCLUDE)))
975                         continue;
976
977                 if (baselen >= matchlen) {
978                         /* If it doesn't match, move along... */
979                         if (!match_dir_prefix(item, base_str, match, matchlen))
980                                 goto match_wildcards;
981
982                         if (!ps->recursive ||
983                             !(ps->magic & PATHSPEC_MAXDEPTH) ||
984                             ps->max_depth == -1)
985                                 return all_entries_interesting;
986
987                         return within_depth(base_str + matchlen + 1,
988                                             baselen - matchlen - 1,
989                                             !!S_ISDIR(entry->mode),
990                                             ps->max_depth) ?
991                                 entry_interesting : entry_not_interesting;
992                 }
993
994                 /* Either there must be no base, or the base must match. */
995                 if (baselen == 0 || !basecmp(item, base_str, match, baselen)) {
996                         if (match_entry(item, entry, pathlen,
997                                         match + baselen, matchlen - baselen,
998                                         &never_interesting))
999                                 return entry_interesting;
1000
1001                         if (item->nowildcard_len < item->len) {
1002                                 if (!git_fnmatch(item, match + baselen, entry->path,
1003                                                  item->nowildcard_len - baselen))
1004                                         return entry_interesting;
1005
1006                                 /*
1007                                  * Match all directories. We'll try to
1008                                  * match files later on.
1009                                  */
1010                                 if (ps->recursive && S_ISDIR(entry->mode))
1011                                         return entry_interesting;
1012
1013                                 /*
1014                                  * When matching against submodules with
1015                                  * wildcard characters, ensure that the entry
1016                                  * at least matches up to the first wild
1017                                  * character.  More accurate matching can then
1018                                  * be performed in the submodule itself.
1019                                  */
1020                                 if (ps->recursive && S_ISGITLINK(entry->mode) &&
1021                                     !ps_strncmp(item, match + baselen,
1022                                                 entry->path,
1023                                                 item->nowildcard_len - baselen))
1024                                         return entry_interesting;
1025                         }
1026
1027                         continue;
1028                 }
1029
1030 match_wildcards:
1031                 if (item->nowildcard_len == item->len)
1032                         continue;
1033
1034                 if (item->nowildcard_len &&
1035                     !match_wildcard_base(item, base_str, baselen, &matched))
1036                         continue;
1037
1038                 /*
1039                  * Concatenate base and entry->path into one and do
1040                  * fnmatch() on it.
1041                  *
1042                  * While we could avoid concatenation in certain cases
1043                  * [1], which saves a memcpy and potentially a
1044                  * realloc, it turns out not worth it. Measurement on
1045                  * linux-2.6 does not show any clear improvements,
1046                  * partly because of the nowildcard_len optimization
1047                  * in git_fnmatch(). Avoid micro-optimizations here.
1048                  *
1049                  * [1] if match_wildcard_base() says the base
1050                  * directory is already matched, we only need to match
1051                  * the rest, which is shorter so _in theory_ faster.
1052                  */
1053
1054                 strbuf_add(base, entry->path, pathlen);
1055
1056                 if (!git_fnmatch(item, match, base->buf + base_offset,
1057                                  item->nowildcard_len)) {
1058                         strbuf_setlen(base, base_offset + baselen);
1059                         return entry_interesting;
1060                 }
1061
1062                 /*
1063                  * When matching against submodules with
1064                  * wildcard characters, ensure that the entry
1065                  * at least matches up to the first wild
1066                  * character.  More accurate matching can then
1067                  * be performed in the submodule itself.
1068                  */
1069                 if (ps->recursive && S_ISGITLINK(entry->mode) &&
1070                     !ps_strncmp(item, match, base->buf + base_offset,
1071                                 item->nowildcard_len)) {
1072                         strbuf_setlen(base, base_offset + baselen);
1073                         return entry_interesting;
1074                 }
1075
1076                 strbuf_setlen(base, base_offset + baselen);
1077
1078                 /*
1079                  * Match all directories. We'll try to match files
1080                  * later on.
1081                  * max_depth is ignored but we may consider support it
1082                  * in future, see
1083                  * https://public-inbox.org/git/7vmxo5l2g4.fsf@alter.siamese.dyndns.org/
1084                  */
1085                 if (ps->recursive && S_ISDIR(entry->mode))
1086                         return entry_interesting;
1087         }
1088         return never_interesting; /* No matches */
1089 }
1090
1091 /*
1092  * Is a tree entry interesting given the pathspec we have?
1093  *
1094  * Pre-condition: either baselen == base_offset (i.e. empty path)
1095  * or base[baselen-1] == '/' (i.e. with trailing slash).
1096  */
1097 enum interesting tree_entry_interesting(const struct name_entry *entry,
1098                                         struct strbuf *base, int base_offset,
1099                                         const struct pathspec *ps)
1100 {
1101         enum interesting positive, negative;
1102         positive = do_match(entry, base, base_offset, ps, 0);
1103
1104         /*
1105          * case | entry | positive | negative | result
1106          * -----+-------+----------+----------+-------
1107          *   1  |  file |   -1     |  -1..2   |  -1
1108          *   2  |  file |    0     |  -1..2   |   0
1109          *   3  |  file |    1     |   -1     |   1
1110          *   4  |  file |    1     |    0     |   1
1111          *   5  |  file |    1     |    1     |   0
1112          *   6  |  file |    1     |    2     |   0
1113          *   7  |  file |    2     |   -1     |   2
1114          *   8  |  file |    2     |    0     |   2
1115          *   9  |  file |    2     |    1     |   0
1116          *  10  |  file |    2     |    2     |  -1
1117          * -----+-------+----------+----------+-------
1118          *  11  |  dir  |   -1     |  -1..2   |  -1
1119          *  12  |  dir  |    0     |  -1..2   |   0
1120          *  13  |  dir  |    1     |   -1     |   1
1121          *  14  |  dir  |    1     |    0     |   1
1122          *  15  |  dir  |    1     |    1     |   1 (*)
1123          *  16  |  dir  |    1     |    2     |   0
1124          *  17  |  dir  |    2     |   -1     |   2
1125          *  18  |  dir  |    2     |    0     |   2
1126          *  19  |  dir  |    2     |    1     |   1 (*)
1127          *  20  |  dir  |    2     |    2     |  -1
1128          *
1129          * (*) An exclude pattern interested in a directory does not
1130          * necessarily mean it will exclude all of the directory. In
1131          * wildcard case, it can't decide until looking at individual
1132          * files inside. So don't write such directories off yet.
1133          */
1134
1135         if (!(ps->magic & PATHSPEC_EXCLUDE) ||
1136             positive <= entry_not_interesting) /* #1, #2, #11, #12 */
1137                 return positive;
1138
1139         negative = do_match(entry, base, base_offset, ps, 1);
1140
1141         /* #3, #4, #7, #8, #13, #14, #17, #18 */
1142         if (negative <= entry_not_interesting)
1143                 return positive;
1144
1145         /* #15, #19 */
1146         if (S_ISDIR(entry->mode) &&
1147             positive >= entry_interesting &&
1148             negative == entry_interesting)
1149                 return entry_interesting;
1150
1151         if ((positive == entry_interesting &&
1152              negative >= entry_interesting) || /* #5, #6, #16 */
1153             (positive == all_entries_interesting &&
1154              negative == entry_interesting)) /* #9 */
1155                 return entry_not_interesting;
1156
1157         return all_entries_not_interesting; /* #10, #20 */
1158 }