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