dir.c 2.32 KB
Newer Older
Vicent Marti committed
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
Vicent Marti committed
3 4 5 6
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */
7 8 9

#include "dir.h"

10
#define GIT__WIN32_NO_WRAP_DIR
Vicent Marti committed
11
#include "posix.h"
12

13
git__DIR *git__opendir(const char *dir)
14
{
15
	git_win32_path filter_w;
16
	git__DIR *new = NULL;
17
	size_t dirlen, alloclen;
18

19
	if (!dir || !git_win32__findfirstfile_filter(filter_w, dir))
20 21
		return NULL;

22 23
	dirlen = strlen(dir);

24 25 26
	if (GIT_ADD_SIZET_OVERFLOW(&alloclen, sizeof(*new), dirlen) ||
		GIT_ADD_SIZET_OVERFLOW(&alloclen, alloclen, 1) ||
		!(new = git__calloc(1, alloclen)))
27
		return NULL;
28

29
	memcpy(new->dir, dir, dirlen);
30

31 32
	new->h = FindFirstFileW(filter_w, &new->f);

33
	if (new->h == INVALID_HANDLE_VALUE) {
34
		giterr_set(GITERR_OS, "could not open directory '%s'", dir);
35 36
		git__free(new);
		return NULL;
37 38
	}

39
	new->first = 1;
40 41 42
	return new;
}

43 44 45 46 47
int git__readdir_ext(
	git__DIR *d,
	struct git__dirent *entry,
	struct git__dirent **result,
	int *is_dir)
48
{
49 50
	if (!d || !entry || !result || d->h == INVALID_HANDLE_VALUE)
		return -1;
51

52 53
	*result = NULL;

54 55
	if (d->first)
		d->first = 0;
56
	else if (!FindNextFileW(d->h, &d->f)) {
57 58
		if (GetLastError() == ERROR_NO_MORE_FILES)
			return 0;
59
		giterr_set(GITERR_OS, "could not read from directory '%s'", d->dir);
60
		return -1;
61 62
	}

63 64
	/* Convert the path to UTF-8 */
	if (git_win32_path_to_utf8(entry->d_name, d->f.cFileName) < 0)
65 66 67
		return -1;

	entry->d_ino = 0;
68

69
	*result = entry;
70

71 72 73
	if (is_dir != NULL)
		*is_dir = ((d->f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);

74 75
	return 0;
}
76

77 78 79
struct git__dirent *git__readdir(git__DIR *d)
{
	struct git__dirent *result;
80
	if (git__readdir_ext(d, &d->entry, &result, NULL) < 0)
81 82
		return NULL;
	return result;
83 84
}

85
void git__rewinddir(git__DIR *d)
86
{
87
	git_win32_path filter_w;
88

89 90 91 92 93
	if (!d)
		return;

	if (d->h != INVALID_HANDLE_VALUE) {
		FindClose(d->h);
94 95
		d->h = INVALID_HANDLE_VALUE;
		d->first = 0;
96
	}
97

98
	if (!git_win32__findfirstfile_filter(filter_w, d->dir))
99
		return;
100

101 102 103
	d->h = FindFirstFileW(filter_w, &d->f);

	if (d->h == INVALID_HANDLE_VALUE)
104
		giterr_set(GITERR_OS, "could not open directory '%s'", d->dir);
105 106
	else
		d->first = 1;
107 108
}

109
int git__closedir(git__DIR *d)
110
{
111 112 113 114 115 116
	if (!d)
		return 0;

	if (d->h != INVALID_HANDLE_VALUE) {
		FindClose(d->h);
		d->h = INVALID_HANDLE_VALUE;
117
	}
118

119
	git__free(d);
120 121 122
	return 0;
}