-
Notifications
You must be signed in to change notification settings - Fork 1
/
monitorfile_winlean.nim
86 lines (72 loc) · 2.66 KB
/
monitorfile_winlean.nim
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
# compile:
# > nim c -r monitorfile.nim
import winlean
const
FILE_NOTIFY_CHANGE_FILE_NAME* = 0x00000001'i32
FILE_NOTIFY_CHANGE_DIR_NAME* = 0x00000002'i32
FILE_NOTIFY_CHANGE_ATTRIBUTES* = 0x00000004'i32
FILE_NOTIFY_CHANGE_SIZE* = 0x00000008'i32
FILE_NOTIFY_CHANGE_LAST_WRITE* = 0x00000010'i32
FILE_NOTIFY_CHANGE_SECURITY* = 0x00000100'i32
{.push dynlib: "kernel32.dll", stdcall.}
proc findFirstChangeNotification(pathname: cstring, watchSubtree: bool,
notifFilter: int32): HANDLE {.importc: "FindFirstChangeNotificationA".}
proc findNextChangeNotification(handle: HANDLE): WINBOOL
{.importc:"FindNextChangeNotification".}
{.pop.}
proc quit(value: DWORD) =
quit value.int
proc refreshDirectory(handle: var HANDLE) =
handle = findFirstChangeNotification(".", false,
FILE_NOTIFY_CHANGE_FILE_NAME + FILE_NOTIFY_CHANGE_SIZE +
FILE_NOTIFY_CHANGE_LAST_WRITE)
if handle == INVALID_HANDLE_VALUE:
quit getLastError()
proc refreshTree(handle: var HANDLE) =
handle = findFirstChangeNotification(".", true,
FILE_NOTIFY_CHANGE_DIR_NAME)
proc waitForMultipleObjects(count: int, handles: var openArray[HANDLE],
waitAll: bool, timeout: int32): int =
echo "to wait for multiple objects"
winlean.waitForMultipleObjects(count.DWORD, cast[PWOHandleArray](addr handles[0]),
waitAll.WINBOOL, cast[DWORD](timeout)).int
proc main =
var
waitStatus: int
changeHandles: array[2, HANDLE]
refreshDirectory(changeHandles[0])
if changeHandles[0] == INVALID_HANDLE_VALUE:
echo "invalid handle value in refresh directory"
quit getLastError()
refreshTree(changeHandles[1])
if changeHandles[1] == INVALID_HANDLE_VALUE:
echo "invalid handle value in refresh tree"
quit getLastError()
echo "Start watching current directory"
while true:
# can handle INFINITE if doing in different thread
waitStatus = waitForMultipleObjects(2, changeHandles, false, 1000)
case waitStatus
of WAIT_OBJECT_0:
echo "A file was created or deleted in this directory"
#refreshDirectory(changeHandles[0])
if findNextChangeNotification(changeHandles[0]) == 0:
var lasterror = getLastError()
echo "lasterror: ", lasterror
quit getLastError()
#break
of WAIT_OBJECT_0 + 1:
echo "A folder was created or deleted in this directory"
#refreshTree(changeHandles[1])
if findNextChangeNotification(changeHandles[1]) == 0:
var lasterror = getLastError()
echo "lasterror: ", lasterror
quit getLastError()
#break
of WAIT_TIMEOUT:
echo "Nothing happened until time out happened"
else:
echo "Into default post"
quit getLastError()
when isMainModule:
main()