1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#ifndef LIVESIDE_WIN32_WATCH_H
#define LIVESIDE_WIN32_WATCH_H
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../ignore/ignore.h"
#define WIN32_WATCH_BUFSZ 65536
typedef struct win32_watch {
HANDLE dir;
char root[IGNORE_PATH_MAX];
ignore_context_t *ignore;
} win32_watch_t;
static win32_watch_t *
win32_watch_open(const char *root, ignore_context_t *ignore)
{
win32_watch_t *w = (win32_watch_t *)calloc(1, sizeof(*w));
if (!w)
return NULL;
snprintf(w->root, sizeof(w->root), "%s", root);
w->ignore = ignore;
w->dir = CreateFileA(root, FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (w->dir == INVALID_HANDLE_VALUE) {
free(w);
return NULL;
}
return w;
}
static bool
win32_watch_event_ignored(win32_watch_t *w,
const FILE_NOTIFY_INFORMATION *fni)
{
char name[IGNORE_PATH_MAX];
int n = WideCharToMultiByte(CP_UTF8, 0, fni->FileName,
(int)(fni->FileNameLength / sizeof(WCHAR)), name,
(int)sizeof(name) - 1, NULL, NULL);
if (n <= 0)
return false;
name[n] = '\0';
for (char *p = name; *p; p++)
if (*p == '\\')
*p = '/';
char full[IGNORE_PATH_MAX];
snprintf(full, sizeof(full), "%s/%s", w->root, name);
if (ignore_is_ignore_file(full))
return true;
DWORD attrs = GetFileAttributesA(full);
bool is_dir = attrs != INVALID_FILE_ATTRIBUTES &&
(attrs & FILE_ATTRIBUTE_DIRECTORY) != 0;
return ignore_path_ignored(w->ignore, full, is_dir);
}
static bool
win32_watch_wait(win32_watch_t *w)
{
char buf[WIN32_WATCH_BUFSZ];
DWORD bytes = 0;
DWORD filter = FILE_NOTIFY_CHANGE_FILE_NAME |
FILE_NOTIFY_CHANGE_DIR_NAME |
FILE_NOTIFY_CHANGE_SIZE |
FILE_NOTIFY_CHANGE_LAST_WRITE;
if (!ReadDirectoryChangesW(w->dir, buf, sizeof(buf), TRUE, filter,
&bytes, NULL, NULL))
return false;
if (bytes == 0)
return true;
FILE_NOTIFY_INFORMATION *fni = (FILE_NOTIFY_INFORMATION *)buf;
for (;;) {
if (!win32_watch_event_ignored(w, fni))
return true;
if (fni->NextEntryOffset == 0)
break;
fni = (FILE_NOTIFY_INFORMATION *)((char *)fni + fni->NextEntryOffset);
}
return true;
}
static void
win32_watch_close(win32_watch_t *w)
{
if (!w)
return;
CloseHandle(w->dir);
free(w);
}
#endif /* LIVESIDE_WIN32_WATCH_H */