return 0;
while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL)
- if (get_dtype(e, path) == DT_REG)
+ if (get_dtype(e, path, 0) == DT_REG)
count++;
closedir(dir);
base_path_len = count_path.len;
while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL)
- if (get_dtype(e, &count_path) == DT_DIR &&
+ if (get_dtype(e, &count_path, 0) == DT_DIR &&
strlen(e->d_name) == 2 &&
!hex_to_bytes(&c, e->d_name, 1)) {
strbuf_setlen(&count_path, base_path_len);
strbuf_add_absolute_path(&abspath, at_root ? "." : path);
strbuf_addch(&abspath, '/');
- dtype = get_dtype(e, &abspath);
+ dtype = get_dtype(e, &abspath, 0);
strbuf_setlen(&buf, len);
strbuf_addstr(&buf, e->d_name);
return DT_UNKNOWN;
}
-unsigned char get_dtype(struct dirent *e, struct strbuf *path)
+unsigned char get_dtype(struct dirent *e, struct strbuf *path,
+ int follow_symlink)
{
struct stat st;
unsigned char dtype = DTYPE(e);
size_t base_path_len;
- if (dtype != DT_UNKNOWN)
+ if (dtype != DT_UNKNOWN && !(follow_symlink && dtype == DT_LNK))
return dtype;
- /* d_type unknown in dirent, try to fall back on lstat results */
+ /*
+ * d_type unknown or unfollowed symlink, try to fall back on [l]stat
+ * results. If [l]stat fails, explicitly set DT_UNKNOWN.
+ */
base_path_len = path->len;
strbuf_addstr(path, e->d_name);
- if (lstat(path->buf, &st))
+ if ((follow_symlink && stat(path->buf, &st)) ||
+ (!follow_symlink && lstat(path->buf, &st)))
goto cleanup;
/* determine d_type from st_mode */
* stat.st_mode using the path to the dirent's containing directory (path) and
* the name of the dirent itself.
*
+ * If 'follow_symlink' is 1, this function will attempt to follow DT_LNK types
+ * using 'stat'. Links are *not* followed recursively, so a symlink pointing
+ * to another symlink will still resolve to 'DT_LNK'.
+ *
* Note that 'path' is assumed to have a trailing slash. It is also modified
* in-place during the execution of the function, but is then reverted to its
* original value before returning.
*/
-unsigned char get_dtype(struct dirent *e, struct strbuf *path);
+unsigned char get_dtype(struct dirent *e, struct strbuf *path,
+ int follow_symlink);
/*Count the number of slashes for string s*/
int count_slashes(const char *s);