Reduce cost of deletion in levenstein distance (4 -> 3)
[git.git] / dir.c
1 /*
2  * This handles recursive filename detection with exclude
3  * files, index knowledge etc..
4  *
5  * Copyright (C) Linus Torvalds, 2005-2006
6  *               Junio Hamano, 2005-2006
7  */
8 #include "cache.h"
9 #include "dir.h"
10 #include "refs.h"
11
12 struct path_simplify {
13         int len;
14         const char *path;
15 };
16
17 static int read_directory_recursive(struct dir_struct *dir, const char *path, int len,
18         int check_only, const struct path_simplify *simplify);
19 static int get_dtype(struct dirent *de, const char *path, int len);
20
21 /* helper string functions with support for the ignore_case flag */
22 int strcmp_icase(const char *a, const char *b)
23 {
24         return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
25 }
26
27 int strncmp_icase(const char *a, const char *b, size_t count)
28 {
29         return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
30 }
31
32 int fnmatch_icase(const char *pattern, const char *string, int flags)
33 {
34         return fnmatch(pattern, string, flags | (ignore_case ? FNM_CASEFOLD : 0));
35 }
36
37 static size_t common_prefix_len(const char **pathspec)
38 {
39         const char *n, *first;
40         size_t max = 0;
41
42         if (!pathspec)
43                 return max;
44
45         first = *pathspec;
46         while ((n = *pathspec++)) {
47                 size_t i, len = 0;
48                 for (i = 0; first == n || i < max; i++) {
49                         char c = n[i];
50                         if (!c || c != first[i] || is_glob_special(c))
51                                 break;
52                         if (c == '/')
53                                 len = i + 1;
54                 }
55                 if (first == n || len < max) {
56                         max = len;
57                         if (!max)
58                                 break;
59                 }
60         }
61         return max;
62 }
63
64 /*
65  * Returns a copy of the longest leading path common among all
66  * pathspecs.
67  */
68 char *common_prefix(const char **pathspec)
69 {
70         unsigned long len = common_prefix_len(pathspec);
71
72         return len ? xmemdupz(*pathspec, len) : NULL;
73 }
74
75 int fill_directory(struct dir_struct *dir, const char **pathspec)
76 {
77         size_t len;
78
79         /*
80          * Calculate common prefix for the pathspec, and
81          * use that to optimize the directory walk
82          */
83         len = common_prefix_len(pathspec);
84
85         /* Read the directory and prune it */
86         read_directory(dir, pathspec ? *pathspec : "", len, pathspec);
87         return len;
88 }
89
90 int within_depth(const char *name, int namelen,
91                         int depth, int max_depth)
92 {
93         const char *cp = name, *cpe = name + namelen;
94
95         while (cp < cpe) {
96                 if (*cp++ != '/')
97                         continue;
98                 depth++;
99                 if (depth > max_depth)
100                         return 0;
101         }
102         return 1;
103 }
104
105 /*
106  * Does 'match' match the given name?
107  * A match is found if
108  *
109  * (1) the 'match' string is leading directory of 'name', or
110  * (2) the 'match' string is a wildcard and matches 'name', or
111  * (3) the 'match' string is exactly the same as 'name'.
112  *
113  * and the return value tells which case it was.
114  *
115  * It returns 0 when there is no match.
116  */
117 static int match_one(const char *match, const char *name, int namelen)
118 {
119         int matchlen;
120
121         /* If the match was just the prefix, we matched */
122         if (!*match)
123                 return MATCHED_RECURSIVELY;
124
125         if (ignore_case) {
126                 for (;;) {
127                         unsigned char c1 = tolower(*match);
128                         unsigned char c2 = tolower(*name);
129                         if (c1 == '\0' || is_glob_special(c1))
130                                 break;
131                         if (c1 != c2)
132                                 return 0;
133                         match++;
134                         name++;
135                         namelen--;
136                 }
137         } else {
138                 for (;;) {
139                         unsigned char c1 = *match;
140                         unsigned char c2 = *name;
141                         if (c1 == '\0' || is_glob_special(c1))
142                                 break;
143                         if (c1 != c2)
144                                 return 0;
145                         match++;
146                         name++;
147                         namelen--;
148                 }
149         }
150
151
152         /*
153          * If we don't match the matchstring exactly,
154          * we need to match by fnmatch
155          */
156         matchlen = strlen(match);
157         if (strncmp_icase(match, name, matchlen))
158                 return !fnmatch_icase(match, name, 0) ? MATCHED_FNMATCH : 0;
159
160         if (namelen == matchlen)
161                 return MATCHED_EXACTLY;
162         if (match[matchlen-1] == '/' || name[matchlen] == '/')
163                 return MATCHED_RECURSIVELY;
164         return 0;
165 }
166
167 /*
168  * Given a name and a list of pathspecs, see if the name matches
169  * any of the pathspecs.  The caller is also interested in seeing
170  * all pathspec matches some names it calls this function with
171  * (otherwise the user could have mistyped the unmatched pathspec),
172  * and a mark is left in seen[] array for pathspec element that
173  * actually matched anything.
174  */
175 int match_pathspec(const char **pathspec, const char *name, int namelen,
176                 int prefix, char *seen)
177 {
178         int i, retval = 0;
179
180         if (!pathspec)
181                 return 1;
182
183         name += prefix;
184         namelen -= prefix;
185
186         for (i = 0; pathspec[i] != NULL; i++) {
187                 int how;
188                 const char *match = pathspec[i] + prefix;
189                 if (seen && seen[i] == MATCHED_EXACTLY)
190                         continue;
191                 how = match_one(match, name, namelen);
192                 if (how) {
193                         if (retval < how)
194                                 retval = how;
195                         if (seen && seen[i] < how)
196                                 seen[i] = how;
197                 }
198         }
199         return retval;
200 }
201
202 /*
203  * Does 'match' match the given name?
204  * A match is found if
205  *
206  * (1) the 'match' string is leading directory of 'name', or
207  * (2) the 'match' string is a wildcard and matches 'name', or
208  * (3) the 'match' string is exactly the same as 'name'.
209  *
210  * and the return value tells which case it was.
211  *
212  * It returns 0 when there is no match.
213  */
214 static int match_pathspec_item(const struct pathspec_item *item, int prefix,
215                                const char *name, int namelen)
216 {
217         /* name/namelen has prefix cut off by caller */
218         const char *match = item->match + prefix;
219         int matchlen = item->len - prefix;
220
221         /* If the match was just the prefix, we matched */
222         if (!*match)
223                 return MATCHED_RECURSIVELY;
224
225         if (matchlen <= namelen && !strncmp(match, name, matchlen)) {
226                 if (matchlen == namelen)
227                         return MATCHED_EXACTLY;
228
229                 if (match[matchlen-1] == '/' || name[matchlen] == '/')
230                         return MATCHED_RECURSIVELY;
231         }
232
233         if (item->use_wildcard && !fnmatch(match, name, 0))
234                 return MATCHED_FNMATCH;
235
236         return 0;
237 }
238
239 /*
240  * Given a name and a list of pathspecs, see if the name matches
241  * any of the pathspecs.  The caller is also interested in seeing
242  * all pathspec matches some names it calls this function with
243  * (otherwise the user could have mistyped the unmatched pathspec),
244  * and a mark is left in seen[] array for pathspec element that
245  * actually matched anything.
246  */
247 int match_pathspec_depth(const struct pathspec *ps,
248                          const char *name, int namelen,
249                          int prefix, char *seen)
250 {
251         int i, retval = 0;
252
253         if (!ps->nr) {
254                 if (!ps->recursive || ps->max_depth == -1)
255                         return MATCHED_RECURSIVELY;
256
257                 if (within_depth(name, namelen, 0, ps->max_depth))
258                         return MATCHED_EXACTLY;
259                 else
260                         return 0;
261         }
262
263         name += prefix;
264         namelen -= prefix;
265
266         for (i = ps->nr - 1; i >= 0; i--) {
267                 int how;
268                 if (seen && seen[i] == MATCHED_EXACTLY)
269                         continue;
270                 how = match_pathspec_item(ps->items+i, prefix, name, namelen);
271                 if (ps->recursive && ps->max_depth != -1 &&
272                     how && how != MATCHED_FNMATCH) {
273                         int len = ps->items[i].len;
274                         if (name[len] == '/')
275                                 len++;
276                         if (within_depth(name+len, namelen-len, 0, ps->max_depth))
277                                 how = MATCHED_EXACTLY;
278                         else
279                                 how = 0;
280                 }
281                 if (how) {
282                         if (retval < how)
283                                 retval = how;
284                         if (seen && seen[i] < how)
285                                 seen[i] = how;
286                 }
287         }
288         return retval;
289 }
290
291 static int no_wildcard(const char *string)
292 {
293         return string[strcspn(string, "*?[{\\")] == '\0';
294 }
295
296 void add_exclude(const char *string, const char *base,
297                  int baselen, struct exclude_list *which)
298 {
299         struct exclude *x;
300         size_t len;
301         int to_exclude = 1;
302         int flags = 0;
303
304         if (*string == '!') {
305                 to_exclude = 0;
306                 string++;
307         }
308         len = strlen(string);
309         if (len && string[len - 1] == '/') {
310                 char *s;
311                 x = xmalloc(sizeof(*x) + len);
312                 s = (char *)(x+1);
313                 memcpy(s, string, len - 1);
314                 s[len - 1] = '\0';
315                 string = s;
316                 x->pattern = s;
317                 flags = EXC_FLAG_MUSTBEDIR;
318         } else {
319                 x = xmalloc(sizeof(*x));
320                 x->pattern = string;
321         }
322         x->to_exclude = to_exclude;
323         x->patternlen = strlen(string);
324         x->base = base;
325         x->baselen = baselen;
326         x->flags = flags;
327         if (!strchr(string, '/'))
328                 x->flags |= EXC_FLAG_NODIR;
329         if (no_wildcard(string))
330                 x->flags |= EXC_FLAG_NOWILDCARD;
331         if (*string == '*' && no_wildcard(string+1))
332                 x->flags |= EXC_FLAG_ENDSWITH;
333         ALLOC_GROW(which->excludes, which->nr + 1, which->alloc);
334         which->excludes[which->nr++] = x;
335 }
336
337 static void *read_skip_worktree_file_from_index(const char *path, size_t *size)
338 {
339         int pos, len;
340         unsigned long sz;
341         enum object_type type;
342         void *data;
343         struct index_state *istate = &the_index;
344
345         len = strlen(path);
346         pos = index_name_pos(istate, path, len);
347         if (pos < 0)
348                 return NULL;
349         if (!ce_skip_worktree(istate->cache[pos]))
350                 return NULL;
351         data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
352         if (!data || type != OBJ_BLOB) {
353                 free(data);
354                 return NULL;
355         }
356         *size = xsize_t(sz);
357         return data;
358 }
359
360 void free_excludes(struct exclude_list *el)
361 {
362         int i;
363
364         for (i = 0; i < el->nr; i++)
365                 free(el->excludes[i]);
366         free(el->excludes);
367
368         el->nr = 0;
369         el->excludes = NULL;
370 }
371
372 int add_excludes_from_file_to_list(const char *fname,
373                                    const char *base,
374                                    int baselen,
375                                    char **buf_p,
376                                    struct exclude_list *which,
377                                    int check_index)
378 {
379         struct stat st;
380         int fd, i;
381         size_t size = 0;
382         char *buf, *entry;
383
384         fd = open(fname, O_RDONLY);
385         if (fd < 0 || fstat(fd, &st) < 0) {
386                 if (0 <= fd)
387                         close(fd);
388                 if (!check_index ||
389                     (buf = read_skip_worktree_file_from_index(fname, &size)) == NULL)
390                         return -1;
391                 if (size == 0) {
392                         free(buf);
393                         return 0;
394                 }
395                 if (buf[size-1] != '\n') {
396                         buf = xrealloc(buf, size+1);
397                         buf[size++] = '\n';
398                 }
399         }
400         else {
401                 size = xsize_t(st.st_size);
402                 if (size == 0) {
403                         close(fd);
404                         return 0;
405                 }
406                 buf = xmalloc(size+1);
407                 if (read_in_full(fd, buf, size) != size) {
408                         free(buf);
409                         close(fd);
410                         return -1;
411                 }
412                 buf[size++] = '\n';
413                 close(fd);
414         }
415
416         if (buf_p)
417                 *buf_p = buf;
418         entry = buf;
419         for (i = 0; i < size; i++) {
420                 if (buf[i] == '\n') {
421                         if (entry != buf + i && entry[0] != '#') {
422                                 buf[i - (i && buf[i-1] == '\r')] = 0;
423                                 add_exclude(entry, base, baselen, which);
424                         }
425                         entry = buf + i + 1;
426                 }
427         }
428         return 0;
429 }
430
431 void add_excludes_from_file(struct dir_struct *dir, const char *fname)
432 {
433         if (add_excludes_from_file_to_list(fname, "", 0, NULL,
434                                            &dir->exclude_list[EXC_FILE], 0) < 0)
435                 die("cannot use %s as an exclude file", fname);
436 }
437
438 static void prep_exclude(struct dir_struct *dir, const char *base, int baselen)
439 {
440         struct exclude_list *el;
441         struct exclude_stack *stk = NULL;
442         int current;
443
444         if ((!dir->exclude_per_dir) ||
445             (baselen + strlen(dir->exclude_per_dir) >= PATH_MAX))
446                 return; /* too long a path -- ignore */
447
448         /* Pop the ones that are not the prefix of the path being checked. */
449         el = &dir->exclude_list[EXC_DIRS];
450         while ((stk = dir->exclude_stack) != NULL) {
451                 if (stk->baselen <= baselen &&
452                     !strncmp(dir->basebuf, base, stk->baselen))
453                         break;
454                 dir->exclude_stack = stk->prev;
455                 while (stk->exclude_ix < el->nr)
456                         free(el->excludes[--el->nr]);
457                 free(stk->filebuf);
458                 free(stk);
459         }
460
461         /* Read from the parent directories and push them down. */
462         current = stk ? stk->baselen : -1;
463         while (current < baselen) {
464                 struct exclude_stack *stk = xcalloc(1, sizeof(*stk));
465                 const char *cp;
466
467                 if (current < 0) {
468                         cp = base;
469                         current = 0;
470                 }
471                 else {
472                         cp = strchr(base + current + 1, '/');
473                         if (!cp)
474                                 die("oops in prep_exclude");
475                         cp++;
476                 }
477                 stk->prev = dir->exclude_stack;
478                 stk->baselen = cp - base;
479                 stk->exclude_ix = el->nr;
480                 memcpy(dir->basebuf + current, base + current,
481                        stk->baselen - current);
482                 strcpy(dir->basebuf + stk->baselen, dir->exclude_per_dir);
483                 add_excludes_from_file_to_list(dir->basebuf,
484                                                dir->basebuf, stk->baselen,
485                                                &stk->filebuf, el, 1);
486                 dir->exclude_stack = stk;
487                 current = stk->baselen;
488         }
489         dir->basebuf[baselen] = '\0';
490 }
491
492 /* Scan the list and let the last match determine the fate.
493  * Return 1 for exclude, 0 for include and -1 for undecided.
494  */
495 int excluded_from_list(const char *pathname,
496                        int pathlen, const char *basename, int *dtype,
497                        struct exclude_list *el)
498 {
499         int i;
500
501         if (el->nr) {
502                 for (i = el->nr - 1; 0 <= i; i--) {
503                         struct exclude *x = el->excludes[i];
504                         const char *exclude = x->pattern;
505                         int to_exclude = x->to_exclude;
506
507                         if (x->flags & EXC_FLAG_MUSTBEDIR) {
508                                 if (*dtype == DT_UNKNOWN)
509                                         *dtype = get_dtype(NULL, pathname, pathlen);
510                                 if (*dtype != DT_DIR)
511                                         continue;
512                         }
513
514                         if (x->flags & EXC_FLAG_NODIR) {
515                                 /* match basename */
516                                 if (x->flags & EXC_FLAG_NOWILDCARD) {
517                                         if (!strcmp_icase(exclude, basename))
518                                                 return to_exclude;
519                                 } else if (x->flags & EXC_FLAG_ENDSWITH) {
520                                         if (x->patternlen - 1 <= pathlen &&
521                                             !strcmp_icase(exclude + 1, pathname + pathlen - x->patternlen + 1))
522                                                 return to_exclude;
523                                 } else {
524                                         if (fnmatch_icase(exclude, basename, 0) == 0)
525                                                 return to_exclude;
526                                 }
527                         }
528                         else {
529                                 /* match with FNM_PATHNAME:
530                                  * exclude has base (baselen long) implicitly
531                                  * in front of it.
532                                  */
533                                 int baselen = x->baselen;
534                                 if (*exclude == '/')
535                                         exclude++;
536
537                                 if (pathlen < baselen ||
538                                     (baselen && pathname[baselen-1] != '/') ||
539                                     strncmp_icase(pathname, x->base, baselen))
540                                     continue;
541
542                                 if (x->flags & EXC_FLAG_NOWILDCARD) {
543                                         if (!strcmp_icase(exclude, pathname + baselen))
544                                                 return to_exclude;
545                                 } else {
546                                         if (fnmatch_icase(exclude, pathname+baselen,
547                                                     FNM_PATHNAME) == 0)
548                                             return to_exclude;
549                                 }
550                         }
551                 }
552         }
553         return -1; /* undecided */
554 }
555
556 int excluded(struct dir_struct *dir, const char *pathname, int *dtype_p)
557 {
558         int pathlen = strlen(pathname);
559         int st;
560         const char *basename = strrchr(pathname, '/');
561         basename = (basename) ? basename+1 : pathname;
562
563         prep_exclude(dir, pathname, basename-pathname);
564         for (st = EXC_CMDL; st <= EXC_FILE; st++) {
565                 switch (excluded_from_list(pathname, pathlen, basename,
566                                            dtype_p, &dir->exclude_list[st])) {
567                 case 0:
568                         return 0;
569                 case 1:
570                         return 1;
571                 }
572         }
573         return 0;
574 }
575
576 static struct dir_entry *dir_entry_new(const char *pathname, int len)
577 {
578         struct dir_entry *ent;
579
580         ent = xmalloc(sizeof(*ent) + len + 1);
581         ent->len = len;
582         memcpy(ent->name, pathname, len);
583         ent->name[len] = 0;
584         return ent;
585 }
586
587 static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
588 {
589         if (cache_name_exists(pathname, len, ignore_case))
590                 return NULL;
591
592         ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
593         return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
594 }
595
596 struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len)
597 {
598         if (!cache_name_is_other(pathname, len))
599                 return NULL;
600
601         ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
602         return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
603 }
604
605 enum exist_status {
606         index_nonexistent = 0,
607         index_directory,
608         index_gitdir
609 };
610
611 /*
612  * Do not use the alphabetically stored index to look up
613  * the directory name; instead, use the case insensitive
614  * name hash.
615  */
616 static enum exist_status directory_exists_in_index_icase(const char *dirname, int len)
617 {
618         struct cache_entry *ce = index_name_exists(&the_index, dirname, len + 1, ignore_case);
619         unsigned char endchar;
620
621         if (!ce)
622                 return index_nonexistent;
623         endchar = ce->name[len];
624
625         /*
626          * The cache_entry structure returned will contain this dirname
627          * and possibly additional path components.
628          */
629         if (endchar == '/')
630                 return index_directory;
631
632         /*
633          * If there are no additional path components, then this cache_entry
634          * represents a submodule.  Submodules, despite being directories,
635          * are stored in the cache without a closing slash.
636          */
637         if (!endchar && S_ISGITLINK(ce->ce_mode))
638                 return index_gitdir;
639
640         /* This should never be hit, but it exists just in case. */
641         return index_nonexistent;
642 }
643
644 /*
645  * The index sorts alphabetically by entry name, which
646  * means that a gitlink sorts as '\0' at the end, while
647  * a directory (which is defined not as an entry, but as
648  * the files it contains) will sort with the '/' at the
649  * end.
650  */
651 static enum exist_status directory_exists_in_index(const char *dirname, int len)
652 {
653         int pos;
654
655         if (ignore_case)
656                 return directory_exists_in_index_icase(dirname, len);
657
658         pos = cache_name_pos(dirname, len);
659         if (pos < 0)
660                 pos = -pos-1;
661         while (pos < active_nr) {
662                 struct cache_entry *ce = active_cache[pos++];
663                 unsigned char endchar;
664
665                 if (strncmp(ce->name, dirname, len))
666                         break;
667                 endchar = ce->name[len];
668                 if (endchar > '/')
669                         break;
670                 if (endchar == '/')
671                         return index_directory;
672                 if (!endchar && S_ISGITLINK(ce->ce_mode))
673                         return index_gitdir;
674         }
675         return index_nonexistent;
676 }
677
678 /*
679  * When we find a directory when traversing the filesystem, we
680  * have three distinct cases:
681  *
682  *  - ignore it
683  *  - see it as a directory
684  *  - recurse into it
685  *
686  * and which one we choose depends on a combination of existing
687  * git index contents and the flags passed into the directory
688  * traversal routine.
689  *
690  * Case 1: If we *already* have entries in the index under that
691  * directory name, we always recurse into the directory to see
692  * all the files.
693  *
694  * Case 2: If we *already* have that directory name as a gitlink,
695  * we always continue to see it as a gitlink, regardless of whether
696  * there is an actual git directory there or not (it might not
697  * be checked out as a subproject!)
698  *
699  * Case 3: if we didn't have it in the index previously, we
700  * have a few sub-cases:
701  *
702  *  (a) if "show_other_directories" is true, we show it as
703  *      just a directory, unless "hide_empty_directories" is
704  *      also true and the directory is empty, in which case
705  *      we just ignore it entirely.
706  *  (b) if it looks like a git directory, and we don't have
707  *      'no_gitlinks' set we treat it as a gitlink, and show it
708  *      as a directory.
709  *  (c) otherwise, we recurse into it.
710  */
711 enum directory_treatment {
712         show_directory,
713         ignore_directory,
714         recurse_into_directory
715 };
716
717 static enum directory_treatment treat_directory(struct dir_struct *dir,
718         const char *dirname, int len,
719         const struct path_simplify *simplify)
720 {
721         /* The "len-1" is to strip the final '/' */
722         switch (directory_exists_in_index(dirname, len-1)) {
723         case index_directory:
724                 return recurse_into_directory;
725
726         case index_gitdir:
727                 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
728                         return ignore_directory;
729                 return show_directory;
730
731         case index_nonexistent:
732                 if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
733                         break;
734                 if (!(dir->flags & DIR_NO_GITLINKS)) {
735                         unsigned char sha1[20];
736                         if (resolve_gitlink_ref(dirname, "HEAD", sha1) == 0)
737                                 return show_directory;
738                 }
739                 return recurse_into_directory;
740         }
741
742         /* This is the "show_other_directories" case */
743         if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
744                 return show_directory;
745         if (!read_directory_recursive(dir, dirname, len, 1, simplify))
746                 return ignore_directory;
747         return show_directory;
748 }
749
750 /*
751  * This is an inexact early pruning of any recursive directory
752  * reading - if the path cannot possibly be in the pathspec,
753  * return true, and we'll skip it early.
754  */
755 static int simplify_away(const char *path, int pathlen, const struct path_simplify *simplify)
756 {
757         if (simplify) {
758                 for (;;) {
759                         const char *match = simplify->path;
760                         int len = simplify->len;
761
762                         if (!match)
763                                 break;
764                         if (len > pathlen)
765                                 len = pathlen;
766                         if (!memcmp(path, match, len))
767                                 return 0;
768                         simplify++;
769                 }
770                 return 1;
771         }
772         return 0;
773 }
774
775 /*
776  * This function tells us whether an excluded path matches a
777  * list of "interesting" pathspecs. That is, whether a path matched
778  * by any of the pathspecs could possibly be ignored by excluding
779  * the specified path. This can happen if:
780  *
781  *   1. the path is mentioned explicitly in the pathspec
782  *
783  *   2. the path is a directory prefix of some element in the
784  *      pathspec
785  */
786 static int exclude_matches_pathspec(const char *path, int len,
787                 const struct path_simplify *simplify)
788 {
789         if (simplify) {
790                 for (; simplify->path; simplify++) {
791                         if (len == simplify->len
792                             && !memcmp(path, simplify->path, len))
793                                 return 1;
794                         if (len < simplify->len
795                             && simplify->path[len] == '/'
796                             && !memcmp(path, simplify->path, len))
797                                 return 1;
798                 }
799         }
800         return 0;
801 }
802
803 static int get_index_dtype(const char *path, int len)
804 {
805         int pos;
806         struct cache_entry *ce;
807
808         ce = cache_name_exists(path, len, 0);
809         if (ce) {
810                 if (!ce_uptodate(ce))
811                         return DT_UNKNOWN;
812                 if (S_ISGITLINK(ce->ce_mode))
813                         return DT_DIR;
814                 /*
815                  * Nobody actually cares about the
816                  * difference between DT_LNK and DT_REG
817                  */
818                 return DT_REG;
819         }
820
821         /* Try to look it up as a directory */
822         pos = cache_name_pos(path, len);
823         if (pos >= 0)
824                 return DT_UNKNOWN;
825         pos = -pos-1;
826         while (pos < active_nr) {
827                 ce = active_cache[pos++];
828                 if (strncmp(ce->name, path, len))
829                         break;
830                 if (ce->name[len] > '/')
831                         break;
832                 if (ce->name[len] < '/')
833                         continue;
834                 if (!ce_uptodate(ce))
835                         break;  /* continue? */
836                 return DT_DIR;
837         }
838         return DT_UNKNOWN;
839 }
840
841 static int get_dtype(struct dirent *de, const char *path, int len)
842 {
843         int dtype = de ? DTYPE(de) : DT_UNKNOWN;
844         struct stat st;
845
846         if (dtype != DT_UNKNOWN)
847                 return dtype;
848         dtype = get_index_dtype(path, len);
849         if (dtype != DT_UNKNOWN)
850                 return dtype;
851         if (lstat(path, &st))
852                 return dtype;
853         if (S_ISREG(st.st_mode))
854                 return DT_REG;
855         if (S_ISDIR(st.st_mode))
856                 return DT_DIR;
857         if (S_ISLNK(st.st_mode))
858                 return DT_LNK;
859         return dtype;
860 }
861
862 enum path_treatment {
863         path_ignored,
864         path_handled,
865         path_recurse
866 };
867
868 static enum path_treatment treat_one_path(struct dir_struct *dir,
869                                           struct strbuf *path,
870                                           const struct path_simplify *simplify,
871                                           int dtype, struct dirent *de)
872 {
873         int exclude = excluded(dir, path->buf, &dtype);
874         if (exclude && (dir->flags & DIR_COLLECT_IGNORED)
875             && exclude_matches_pathspec(path->buf, path->len, simplify))
876                 dir_add_ignored(dir, path->buf, path->len);
877
878         /*
879          * Excluded? If we don't explicitly want to show
880          * ignored files, ignore it
881          */
882         if (exclude && !(dir->flags & DIR_SHOW_IGNORED))
883                 return path_ignored;
884
885         if (dtype == DT_UNKNOWN)
886                 dtype = get_dtype(de, path->buf, path->len);
887
888         /*
889          * Do we want to see just the ignored files?
890          * We still need to recurse into directories,
891          * even if we don't ignore them, since the
892          * directory may contain files that we do..
893          */
894         if (!exclude && (dir->flags & DIR_SHOW_IGNORED)) {
895                 if (dtype != DT_DIR)
896                         return path_ignored;
897         }
898
899         switch (dtype) {
900         default:
901                 return path_ignored;
902         case DT_DIR:
903                 strbuf_addch(path, '/');
904                 switch (treat_directory(dir, path->buf, path->len, simplify)) {
905                 case show_directory:
906                         if (exclude != !!(dir->flags
907                                           & DIR_SHOW_IGNORED))
908                                 return path_ignored;
909                         break;
910                 case recurse_into_directory:
911                         return path_recurse;
912                 case ignore_directory:
913                         return path_ignored;
914                 }
915                 break;
916         case DT_REG:
917         case DT_LNK:
918                 break;
919         }
920         return path_handled;
921 }
922
923 static enum path_treatment treat_path(struct dir_struct *dir,
924                                       struct dirent *de,
925                                       struct strbuf *path,
926                                       int baselen,
927                                       const struct path_simplify *simplify)
928 {
929         int dtype;
930
931         if (is_dot_or_dotdot(de->d_name) || !strcmp(de->d_name, ".git"))
932                 return path_ignored;
933         strbuf_setlen(path, baselen);
934         strbuf_addstr(path, de->d_name);
935         if (simplify_away(path->buf, path->len, simplify))
936                 return path_ignored;
937
938         dtype = DTYPE(de);
939         return treat_one_path(dir, path, simplify, dtype, de);
940 }
941
942 /*
943  * Read a directory tree. We currently ignore anything but
944  * directories, regular files and symlinks. That's because git
945  * doesn't handle them at all yet. Maybe that will change some
946  * day.
947  *
948  * Also, we ignore the name ".git" (even if it is not a directory).
949  * That likely will not change.
950  */
951 static int read_directory_recursive(struct dir_struct *dir,
952                                     const char *base, int baselen,
953                                     int check_only,
954                                     const struct path_simplify *simplify)
955 {
956         DIR *fdir;
957         int contents = 0;
958         struct dirent *de;
959         struct strbuf path = STRBUF_INIT;
960
961         strbuf_add(&path, base, baselen);
962
963         fdir = opendir(path.len ? path.buf : ".");
964         if (!fdir)
965                 goto out;
966
967         while ((de = readdir(fdir)) != NULL) {
968                 switch (treat_path(dir, de, &path, baselen, simplify)) {
969                 case path_recurse:
970                         contents += read_directory_recursive(dir, path.buf,
971                                                              path.len, 0,
972                                                              simplify);
973                         continue;
974                 case path_ignored:
975                         continue;
976                 case path_handled:
977                         break;
978                 }
979                 contents++;
980                 if (check_only)
981                         break;
982                 dir_add_name(dir, path.buf, path.len);
983         }
984         closedir(fdir);
985  out:
986         strbuf_release(&path);
987
988         return contents;
989 }
990
991 static int cmp_name(const void *p1, const void *p2)
992 {
993         const struct dir_entry *e1 = *(const struct dir_entry **)p1;
994         const struct dir_entry *e2 = *(const struct dir_entry **)p2;
995
996         return cache_name_compare(e1->name, e1->len,
997                                   e2->name, e2->len);
998 }
999
1000 /*
1001  * Return the length of the "simple" part of a path match limiter.
1002  */
1003 static int simple_length(const char *match)
1004 {
1005         int len = -1;
1006
1007         for (;;) {
1008                 unsigned char c = *match++;
1009                 len++;
1010                 if (c == '\0' || is_glob_special(c))
1011                         return len;
1012         }
1013 }
1014
1015 static struct path_simplify *create_simplify(const char **pathspec)
1016 {
1017         int nr, alloc = 0;
1018         struct path_simplify *simplify = NULL;
1019
1020         if (!pathspec)
1021                 return NULL;
1022
1023         for (nr = 0 ; ; nr++) {
1024                 const char *match;
1025                 if (nr >= alloc) {
1026                         alloc = alloc_nr(alloc);
1027                         simplify = xrealloc(simplify, alloc * sizeof(*simplify));
1028                 }
1029                 match = *pathspec++;
1030                 if (!match)
1031                         break;
1032                 simplify[nr].path = match;
1033                 simplify[nr].len = simple_length(match);
1034         }
1035         simplify[nr].path = NULL;
1036         simplify[nr].len = 0;
1037         return simplify;
1038 }
1039
1040 static void free_simplify(struct path_simplify *simplify)
1041 {
1042         free(simplify);
1043 }
1044
1045 static int treat_leading_path(struct dir_struct *dir,
1046                               const char *path, int len,
1047                               const struct path_simplify *simplify)
1048 {
1049         struct strbuf sb = STRBUF_INIT;
1050         int baselen, rc = 0;
1051         const char *cp;
1052
1053         while (len && path[len - 1] == '/')
1054                 len--;
1055         if (!len)
1056                 return 1;
1057         baselen = 0;
1058         while (1) {
1059                 cp = path + baselen + !!baselen;
1060                 cp = memchr(cp, '/', path + len - cp);
1061                 if (!cp)
1062                         baselen = len;
1063                 else
1064                         baselen = cp - path;
1065                 strbuf_setlen(&sb, 0);
1066                 strbuf_add(&sb, path, baselen);
1067                 if (!is_directory(sb.buf))
1068                         break;
1069                 if (simplify_away(sb.buf, sb.len, simplify))
1070                         break;
1071                 if (treat_one_path(dir, &sb, simplify,
1072                                    DT_DIR, NULL) == path_ignored)
1073                         break; /* do not recurse into it */
1074                 if (len <= baselen) {
1075                         rc = 1;
1076                         break; /* finished checking */
1077                 }
1078         }
1079         strbuf_release(&sb);
1080         return rc;
1081 }
1082
1083 int read_directory(struct dir_struct *dir, const char *path, int len, const char **pathspec)
1084 {
1085         struct path_simplify *simplify;
1086
1087         if (has_symlink_leading_path(path, len))
1088                 return dir->nr;
1089
1090         simplify = create_simplify(pathspec);
1091         if (!len || treat_leading_path(dir, path, len, simplify))
1092                 read_directory_recursive(dir, path, len, 0, simplify);
1093         free_simplify(simplify);
1094         qsort(dir->entries, dir->nr, sizeof(struct dir_entry *), cmp_name);
1095         qsort(dir->ignored, dir->ignored_nr, sizeof(struct dir_entry *), cmp_name);
1096         return dir->nr;
1097 }
1098
1099 int file_exists(const char *f)
1100 {
1101         struct stat sb;
1102         return lstat(f, &sb) == 0;
1103 }
1104
1105 /*
1106  * Given two normalized paths (a trailing slash is ok), if subdir is
1107  * outside dir, return -1.  Otherwise return the offset in subdir that
1108  * can be used as relative path to dir.
1109  */
1110 int dir_inside_of(const char *subdir, const char *dir)
1111 {
1112         int offset = 0;
1113
1114         assert(dir && subdir && *dir && *subdir);
1115
1116         while (*dir && *subdir && *dir == *subdir) {
1117                 dir++;
1118                 subdir++;
1119                 offset++;
1120         }
1121
1122         /* hel[p]/me vs hel[l]/yeah */
1123         if (*dir && *subdir)
1124                 return -1;
1125
1126         if (!*subdir)
1127                 return !*dir ? offset : -1; /* same dir */
1128
1129         /* foo/[b]ar vs foo/[] */
1130         if (is_dir_sep(dir[-1]))
1131                 return is_dir_sep(subdir[-1]) ? offset : -1;
1132
1133         /* foo[/]bar vs foo[] */
1134         return is_dir_sep(*subdir) ? offset + 1 : -1;
1135 }
1136
1137 int is_inside_dir(const char *dir)
1138 {
1139         char cwd[PATH_MAX];
1140         if (!dir)
1141                 return 0;
1142         if (!getcwd(cwd, sizeof(cwd)))
1143                 die_errno("can't find the current directory");
1144         return dir_inside_of(cwd, dir) >= 0;
1145 }
1146
1147 int is_empty_dir(const char *path)
1148 {
1149         DIR *dir = opendir(path);
1150         struct dirent *e;
1151         int ret = 1;
1152
1153         if (!dir)
1154                 return 0;
1155
1156         while ((e = readdir(dir)) != NULL)
1157                 if (!is_dot_or_dotdot(e->d_name)) {
1158                         ret = 0;
1159                         break;
1160                 }
1161
1162         closedir(dir);
1163         return ret;
1164 }
1165
1166 static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
1167 {
1168         DIR *dir;
1169         struct dirent *e;
1170         int ret = 0, original_len = path->len, len, kept_down = 0;
1171         int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1172         int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1173         unsigned char submodule_head[20];
1174
1175         if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
1176             !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
1177                 /* Do not descend and nuke a nested git work tree. */
1178                 if (kept_up)
1179                         *kept_up = 1;
1180                 return 0;
1181         }
1182
1183         flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
1184         dir = opendir(path->buf);
1185         if (!dir) {
1186                 /* an empty dir could be removed even if it is unreadble */
1187                 if (!keep_toplevel)
1188                         return rmdir(path->buf);
1189                 else
1190                         return -1;
1191         }
1192         if (path->buf[original_len - 1] != '/')
1193                 strbuf_addch(path, '/');
1194
1195         len = path->len;
1196         while ((e = readdir(dir)) != NULL) {
1197                 struct stat st;
1198                 if (is_dot_or_dotdot(e->d_name))
1199                         continue;
1200
1201                 strbuf_setlen(path, len);
1202                 strbuf_addstr(path, e->d_name);
1203                 if (lstat(path->buf, &st))
1204                         ; /* fall thru */
1205                 else if (S_ISDIR(st.st_mode)) {
1206                         if (!remove_dir_recurse(path, flag, &kept_down))
1207                                 continue; /* happy */
1208                 } else if (!only_empty && !unlink(path->buf))
1209                         continue; /* happy, too */
1210
1211                 /* path too long, stat fails, or non-directory still exists */
1212                 ret = -1;
1213                 break;
1214         }
1215         closedir(dir);
1216
1217         strbuf_setlen(path, original_len);
1218         if (!ret && !keep_toplevel && !kept_down)
1219                 ret = rmdir(path->buf);
1220         else if (kept_up)
1221                 /*
1222                  * report the uplevel that it is not an error that we
1223                  * did not rmdir() our directory.
1224                  */
1225                 *kept_up = !ret;
1226         return ret;
1227 }
1228
1229 int remove_dir_recursively(struct strbuf *path, int flag)
1230 {
1231         return remove_dir_recurse(path, flag, NULL);
1232 }
1233
1234 void setup_standard_excludes(struct dir_struct *dir)
1235 {
1236         const char *path;
1237
1238         dir->exclude_per_dir = ".gitignore";
1239         path = git_path("info/exclude");
1240         if (!access(path, R_OK))
1241                 add_excludes_from_file(dir, path);
1242         if (excludes_file && !access(excludes_file, R_OK))
1243                 add_excludes_from_file(dir, excludes_file);
1244 }
1245
1246 int remove_path(const char *name)
1247 {
1248         char *slash;
1249
1250         if (unlink(name) && errno != ENOENT)
1251                 return -1;
1252
1253         slash = strrchr(name, '/');
1254         if (slash) {
1255                 char *dirs = xstrdup(name);
1256                 slash = dirs + (slash - name);
1257                 do {
1258                         *slash = '\0';
1259                 } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
1260                 free(dirs);
1261         }
1262         return 0;
1263 }
1264
1265 static int pathspec_item_cmp(const void *a_, const void *b_)
1266 {
1267         struct pathspec_item *a, *b;
1268
1269         a = (struct pathspec_item *)a_;
1270         b = (struct pathspec_item *)b_;
1271         return strcmp(a->match, b->match);
1272 }
1273
1274 int init_pathspec(struct pathspec *pathspec, const char **paths)
1275 {
1276         const char **p = paths;
1277         int i;
1278
1279         memset(pathspec, 0, sizeof(*pathspec));
1280         if (!p)
1281                 return 0;
1282         while (*p)
1283                 p++;
1284         pathspec->raw = paths;
1285         pathspec->nr = p - paths;
1286         if (!pathspec->nr)
1287                 return 0;
1288
1289         pathspec->items = xmalloc(sizeof(struct pathspec_item)*pathspec->nr);
1290         for (i = 0; i < pathspec->nr; i++) {
1291                 struct pathspec_item *item = pathspec->items+i;
1292                 const char *path = paths[i];
1293
1294                 item->match = path;
1295                 item->len = strlen(path);
1296                 item->use_wildcard = !no_wildcard(path);
1297                 if (item->use_wildcard)
1298                         pathspec->has_wildcard = 1;
1299         }
1300
1301         qsort(pathspec->items, pathspec->nr,
1302               sizeof(struct pathspec_item), pathspec_item_cmp);
1303
1304         return 0;
1305 }
1306
1307 void free_pathspec(struct pathspec *pathspec)
1308 {
1309         free(pathspec->items);
1310         pathspec->items = NULL;
1311 }