-
Notifications
You must be signed in to change notification settings - Fork 18
/
io2.nim
1775 lines (1654 loc) · 57.9 KB
/
io2.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## Copyright (c) 2020-2024 Status Research & Development GmbH
## Licensed under either of
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
## at your option.
## This file may not be copied, modified, or distributed except according to
## those terms.
## This module implements number cross-platform IO and OS procedures which do
## not use exceptions and using Result[T] for error handling.
##
{.push raises: [].}
import std/algorithm
import pkg/results
export results
when defined(windows):
from strutils import replace, find
const
GENERIC_READ = 0x80000000'u32
GENERIC_WRITE = 0x40000000'u32
CREATE_NEW = 1'u32
CREATE_ALWAYS = 2'u32
OPEN_EXISTING = 3'u32
OPEN_ALWAYS = 4'u32
TRUNCATE_EXISTING = 5'u32
FILE_FLAG_OVERLAPPED = 0x40000000'u32
FILE_SHARE_READ = 0x00000001'u32
FILE_SHARE_WRITE = 0x00000002'u32
FILE_APPEND_DATA = 0x00000004'u32
FILE_FLAG_NO_BUFFERING = 0x20000000'u32
FILE_FLAG_WRITE_THROUGH = 0x80000000'u32
FILE_ATTRIBUTE_READONLY = 0x00000001'u32
FILE_ATTRIBUTE_DIRECTORY = 0x00000010'u32
INVALID_HANDLE_VALUE = cast[uint](-1)
INVALID_FILE_SIZE = cast[uint32](-1)
INVALID_FILE_ATTRIBUTES = cast[uint32](-1)
MAX_PATH = 260
ERROR_ALREADY_EXISTS = 183'u32
ERROR_FILE_NOT_FOUND = 2'u32
FILE_BEGIN = 0'u32
FILE_CURRENT = 1'u32
FILE_END = 2'u32
DirSep* = '\\'
AltSep* = '/'
BothSeps* = {DirSep, AltSep}
FileBasicInfoClass = 0'u32
CSIDL_APPDATA = 0x001a'u32
# <user name>\Application Data
CSIDL_PROFILE = 0x0028'u32
# <user name>
CSIDL_LOCAL_APPDATA = 0x001c'u32
# <user name>\Local Settings\Applicaiton Data (non roaming)
type
IoErrorCode* = distinct uint32
IoHandle* = distinct uint
SECURITY_ATTRIBUTES {.final, pure.} = object
nLength: uint32
lpSecurityDescriptor: pointer
bInheritHandle: int32
FILETIME {.final, pure.} = object
dwLowDateTime: uint32
dwHighDateTime: uint32
WIN32_FIND_DATAW {.final, pure.} = object
dwFileAttributes: uint32
ftCreationTime: FILETIME
ftLastAccessTime: FILETIME
ftLastWriteTime: FILETIME
nFileSizeHigh: uint32
nFileSizeLow: uint32
dwReserved0: uint32
dwReserved1: uint32
cFileName: array[MAX_PATH, Utf16Char]
cAlternateFileName: array[14, Utf16Char]
BY_HANDLE_FILE_INFORMATION {.final, pure.} = object
dwFileAttributes: uint32
ftCreationTime: FILETIME
ftLastAccessTime: FILETIME
ftLastWriteTime: FILETIME
dwVolumeSerialNumber: uint32
nFileSizeHigh: uint32
nFileSizeLow: uint32
nNumberOfLinks: uint32
nFileIndexHigh: uint32
nFileIndexLow: uint32
FILE_BASIC_INFO {.final, pure.} = object
creationTime: uint64
lastAccessTime: uint64
lastWriteTime: uint64
changeTime: uint64
fileAttributes: uint32
OVERLAPPED* {.pure, inheritable.} = object
internal*: uint
internalHigh*: uint
offset*: uint32
offsetHigh*: uint32
hEvent*: IoHandle
proc getLastError(): uint32 {.
importc: "GetLastError", stdcall, dynlib: "kernel32", sideEffect.}
proc createDirectoryW(pathName: WideCString,
security: var SECURITY_ATTRIBUTES): int32 {.
importc: "CreateDirectoryW", dynlib: "kernel32", stdcall, sideEffect.}
proc removeDirectoryW(pathName: WideCString): int32 {.
importc: "RemoveDirectoryW", dynlib: "kernel32", stdcall, sideEffect.}
proc createFileW(fileName: WideCString, dwDesiredAccess: uint32,
dwShareMode: uint32, security: var SECURITY_ATTRIBUTES,
dwCreationDisposition: uint32, dwFlagsAndAttributes: uint32,
hTemplateFile: uint): uint {.
importc: "CreateFileW", dynlib: "kernel32", stdcall, sideEffect.}
proc deleteFileW(pathName: WideCString): uint32 {.
importc: "DeleteFileW", dynlib: "kernel32", stdcall.}
proc closeHandle(hobj: uint): int32 {.
importc: "CloseHandle", dynlib: "kernel32", stdcall, sideEffect.}
proc writeFile(hFile: uint, lpBuffer: pointer,
nNumberOfBytesToWrite: uint32,
lpNumberOfBytesWritten: var uint32,
lpOverlapped: pointer): int32 {.
importc: "WriteFile", dynlib: "kernel32", stdcall, sideEffect.}
proc readFile(hFile: uint, lpBuffer: pointer,
nNumberOfBytesToRead: uint32,
lpNumberOfBytesRead: var uint32,
lpOverlapped: pointer): int32 {.
importc: "ReadFile", dynlib: "kernel32", stdcall, sideEffect.}
proc getFileAttributes(path: WideCString): uint32 {.
importc: "GetFileAttributesW", dynlib: "kernel32", stdcall, sideEffect.}
proc setFileAttributes(path: WideCString, dwAttributes: uint32): uint32 {.
importc: "SetFileAttributesW", dynlib: "kernel32", stdcall, sideEffect.}
proc getCurrentDirectoryW(nBufferLength: uint32,
lpBuffer: WideCString): uint32 {.
importc: "GetCurrentDirectoryW", dynlib: "kernel32", stdcall,
sideEffect.}
proc formatMessageW(dwFlags: uint32, lpSource: pointer,
dwMessageId, dwLanguageId: uint32,
lpBuffer: pointer, nSize: uint32,
arguments: pointer): uint32 {.
importc: "FormatMessageW", stdcall, dynlib: "kernel32".}
proc localFree(p: pointer): uint {.
importc: "LocalFree", stdcall, dynlib: "kernel32", sideEffect.}
proc getLongPathNameW(lpszShortPath: WideCString, lpszLongPath: WideCString,
cchBuffer: uint32): uint32 {.
importc: "GetLongPathNameW", dynlib: "kernel32.dll", stdcall,
sideEffect.}
proc findFirstFileW(lpFileName: WideCString,
lpFindFileData: var WIN32_FIND_DATAW): uint {.
importc: "FindFirstFileW", dynlib: "kernel32", stdcall, sideEffect.}
proc findClose(hFindFile: uint): int32 {.
importc: "FindClose", dynlib: "kernel32", stdcall, sideEffect.}
proc getFileInformationByHandle(hFile: uint,
info: var BY_HANDLE_FILE_INFORMATION): int32 {.
importc: "GetFileInformationByHandle", dynlib: "kernel32", stdcall,
sideEffect.}
proc getFileInformationByHandleEx(hFile: uint, information: uint32,
lpFileInformation: pointer,
dwBufferSize: uint32): int32 {.
importc: "GetFileInformationByHandleEx", dynlib: "kernel32", stdcall,
sideEffect.}
proc setFileInformationByHandle(hFile: uint, information: uint32,
lpFileInformation: pointer,
dwBufferSize: uint32): int32 {.
importc: "SetFileInformationByHandle", dynlib: "kernel32", stdcall,
sideEffect.}
proc getFileSize(hFile: uint, lpFileSizeHigh: var uint32): uint32 {.
importc: "GetFileSize", dynlib: "kernel32", stdcall, sideEffect.}
proc setFilePointerEx(hFile: uint, liDistanceToMove: int64,
lpNewFilePointer: ptr int64,
dwMoveMethod: uint32): int32 {.
importc: "SetFilePointerEx", dynlib: "kernel32", stdcall, sideEffect.}
proc setEndOfFile(hFile: uint): int32 {.
importc: "SetEndOfFile", dynlib: "kernel32", stdcall, sideEffect.}
proc lockFileEx(hFile: uint, dwFlags, dwReserved: uint32,
nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh: uint32,
lpOverlapped: pointer): uint32 {.
importc: "LockFileEx", dynlib: "kernel32", stdcall, sideEffect.}
proc unlockFileEx(hFile: uint, dwReserved: uint32,
nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh: uint32,
lpOverlapped: pointer): uint32 {.
importc: "UnlockFileEx", dynlib: "kernel32", stdcall, sideEffect.}
proc shGetSpecialFolderPathW(hwnd: uint, pszPath: WideCString, csidl: uint32,
fCreate: uint32):uint32 {.
importc: "SHGetSpecialFolderPathW", dynlib: "shell32", stdcall,
sideEffect.}
proc getTempPathW(nBufferLength: uint32, lpBuffer: WideCString): uint32 {.
importc: "GetTempPathW", dynlib: "kernel32", stdcall, sideEffect.}
proc flushFileBuffers(hFile: uint): int32 {.
importc: "FlushFileBuffers", dynlib: "kernel32", stdcall, sideEffect.}
const
NO_ERROR = IoErrorCode(0)
LOCKFILE_EXCLUSIVE_LOCK = 0x00000002'u32
LOCKFILE_FAIL_IMMEDIATELY = 0x00000001'u32
proc `==`*(a: IoErrorCode, b: uint32): bool {.inline.} =
(uint32(a) == b)
elif defined(posix):
import posix
const
DirSep* = '/'
AltSep* = '/'
BothSeps* = {'/'}
LOCK_SH* = 0x01
LOCK_EX* = 0x02
LOCK_NB* = 0x04
LOCK_UN* = 0x08
type
IoHandle* = distinct cint
IoErrorCode* = distinct cint
when defined(linux):
const
O_DIRECT = cint(0x4000)
O_CLOEXEC = cint(0x2000000)
elif defined(freebsd):
const
O_DIRECT = cint(0x10000)
O_CLOEXEC = cint(0x100000)
elif defined(dragonflybsd):
const
O_DIRECT = cint(0x10000)
O_CLOEXEC = cint(0x20000)
elif defined(netbsd):
const
O_DIRECT = cint(0x80000)
O_CLOEXEC = cint(0x400000)
elif defined(openbsd):
const
O_CLOEXEC = cint(0x10000)
elif defined(macosx):
const
O_CLOEXEC = cint(0x1000000)
F_NOCACHE = cint(48)
type
FlockStruct* {.importc: "struct flock", final, pure,
header: "<fcntl.h>".} = object
ltype* {.importc: "l_type".}: cshort
lwhence* {.importc: "l_whence".}: cshort
start* {.importc: "l_start".}: int
length* {.importc: "l_len".}: int
pid* {.importc: "l_pid".}: int32
var errno {.importc, header: "<errno.h>".}: cint
proc c_getenv(env: cstring): cstring {.
importc: "getenv", header: "<stdlib.h>", sideEffect.}
proc write(a1: cint, a2: pointer, a3: csize_t): int {.
importc, header: "<unistd.h>", sideEffect.}
proc read(a1: cint, a2: pointer, a3: csize_t): int {.
importc, header: "<unistd.h>", sideEffect.}
proc c_strerror(errnum: cint): cstring {.
importc: "strerror", header: "<string.h>", sideEffect.}
proc c_free(p: pointer) {.
importc: "free", header: "<stdlib.h>", sideEffect.}
proc getcwd(a1: cstring, a2: int): cstring {.
importc, header: "<unistd.h>", sideEffect.}
proc `==`*(a: IoErrorCode, b: cint): bool {.inline.} =
(cint(a) == b)
type
IoResult*[T] = Result[T, IoErrorCode]
OpenFlags* {.pure.} = enum
Read, Write, Create, Exclusive, Append, Truncate,
Inherit, NonBlock, Direct, ShareRead, ShareWrite
Permission* = enum
UserRead, UserWrite, UserExec,
GroupRead, GroupWrite, GroupExec,
OtherRead, OtherWrite, OtherExec
Permissions* = set[Permission]
SeekPosition* = enum
SeekBegin, SeekCurrent, SeekEnd
AccessFlags* {.pure.} = enum
Find, Read, Write, Execute
LockType* {.pure.} = enum
Shared, Exclusive
IoLockHandle* = object
handle*: IoHandle
offset*: int64
size*: int64
const
NimErrorCode = 100_000
UnsupportedFileSize* = IoErrorCode(NimErrorCode)
UserErrorCode* = 1_000_000
proc `==`*(a, b: IoErrorCode): bool {.borrow.}
proc `$`*(a: IoErrorCode): string {.borrow.}
{.push stackTrace:off.}
proc ioLastError*(): IoErrorCode {.sideEffect.} =
## Retrieves the last operating system error code.
##
## **Warning**:
## The behaviour of this procedure varies between Windows and POSIX systems.
## On Windows some OS calls can reset the error code to ``0`` causing this
## procedure to return ``0``. It is therefore advised to call this procedure
## immediately after an OS call fails. On POSIX systems this is not a problem.
when defined(nimscript):
discard
elif defined(windows):
IoErrorCode(getLastError())
else:
IoErrorCode(errno)
{.pop.}
proc ioErrorMsg*(code: IoErrorCode): string =
## Converts an OS error code into a human readable string.
if int(code) == 0:
""
elif int(code) >= NimErrorCode:
case code
of UnsupportedFileSize:
"(" & $code & ") " & "File size is unsupported"
else:
"(" & $code & ") " & "Unknown error"
else:
when defined(posix):
$c_strerror(cint(code))
elif defined(windows):
var msgbuf: WideCString
if formatMessageW(0x00000100'u32 or 0x00001000'u32 or 0x00000200'u32,
nil, uint32(code), 0, addr(msgbuf), 0, nil) != 0'u32:
var res = $msgbuf
if not(isNil(msgbuf)):
discard localFree(cast[pointer](msgbuf))
res
else:
""
proc normPathEnd(path: var string, trailingSep: bool) =
## Ensures ``path`` has exactly 0 or 1 trailing `DirSep`, depending on
## ``trailingSep``, and taking care of edge cases: it preservers whether
## a path is absolute or relative, and makes sure trailing sep is `DirSep`,
## not `AltSep`. Trailing `/.` are compressed.
var i = len(path)
if i > 0:
while i >= 1:
if path[i - 1] in BothSeps:
dec(i)
elif path[i - 1] == '.' and (i >= 2) and (path[i - 2] in BothSeps):
dec(i)
else:
break
if trailingSep:
path.setLen(i)
path.add DirSep
elif i > 0:
path.setLen(i)
else:
path = $DirSep
when defined(windows):
proc fixPath(path: string): string =
## If ``path`` is absolute path and length of ``path`` exceedes
## MAX_PATH number of characeters - ``path`` will be prefixed with ``\\?\``
## value which disable all string parsing and send the string that follows
## prefix straight to the file system.
##
## MAX_PATH limitation has different meaning for directory paths, because
## when creating directory 12 characters will be reserved for 8.3 filename,
## that's why we going to apply prefix for all paths which are bigger than
## MAX_PATH - 12.
if len(path) < MAX_PATH - 12: return path
if ((path[0] in {'a' .. 'z', 'A' .. 'Z'}) and path[1] == ':'):
"\\\\?\\" & path
else:
path
proc splitDrive*(path: string): tuple[head: string, tail: string] =
## Split the pathname ``path`` into drive/UNC sharepoint and relative path
## specifiers.
##
## Returns a 2-tuple (head, tail); either part may be empty.
##
## If the path contained a drive letter, ``head`` will contain everything
## up to and including the colon. e.g. ``splitDrive("c:/dir")`` returns
## ("c:", "/dir").
##
## If the path contained a UNC path, the ``head`` will contain the host name
## and share up to but not including the fourth directory separator
## character. e.g. ``splitDrive("//host/computer/dir")`` returns
## ("//host/computer", "/dir")
##
## Note, paths cannot contain both a drive letter and a UNC path.
when defined(posix):
# On Posix, drive is always empty
("", path)
elif defined(windows):
if len(path) < 2:
return ("", path)
let normp = path.replace('/', '\\')
if (len(path) > 2) and
normp[0] == '\\' and normp[1] == '\\' and normp[2] != '\\':
let index = normp.find('\\', 2)
if index == -1:
return ("", path)
let index2 = normp.find('\\', index + 1)
if index2 == index + 1:
return ("", path)
return (path[0 ..< index2], path[index2 .. ^1])
if normp[1] == ':':
return (path[0 .. 1], path[2 .. ^1])
return ("", path)
proc splitPath*(path: string): tuple[head: string, tail: string] =
## Split the pathname ``path`` into a pair, (head, tail) where tail is the
## last pathname component and head is everything leading up to that.
##
## * The tail part will never contain a slash.
## * If path ends in a slash, tail will be empty.
## * If there is no slash in path, head will be empty.
## * If path is empty, both head and tail are empty.
## * Trailing slashes are stripped from head unless it is the root
## (one or more slashes only)
if len(path) == 0:
("", "")
else:
let (drive, p) = splitDrive(path)
let pathlen = len(p)
var i = pathlen
while (i != 0) and (p[i - 1]) notin BothSeps:
dec(i)
let head = p[0 ..< i]
let tail = p[i ..< pathlen]
var headStrip = head
i = len(headStrip)
while (i != 0) and (headStrip[i - 1]) in BothSeps:
dec(i)
headStrip.setLen(i)
if len(headStrip) == 0:
(drive & head, tail)
else:
(drive & headStrip, tail)
proc basename*(path: string): string =
## Return the base name of pathname ``path``.
##
## Note that the result of this procedure is different from the Unix basename
## program; where basename for "/foo/bar/" returns "bar", the basename()
## procedure returns an empty string ("").
splitPath(path)[1]
proc dirname*(path: string): string =
## Return the directory name of pathname ``path``.
splitPath(path)[0]
when defined(windows):
proc toLongPath*(path: string): IoResult[string] =
let shortPath = newWideCString(path)
var buffer = newSeq[Utf16Char](len(path) * 2 + 1)
while true:
let res = getLongPathNameW(shortPath, cast[WideCString](addr buffer[0]),
uint32(len(buffer)))
if res == 0:
return err(ioLastError())
else:
if res <= uint32(len(buffer)):
return ok($cast[WideCString](addr buffer[0]))
else:
buffer.setLen(res)
continue
proc getCurrentDir*(): IoResult[string] =
## Returns string containing an absolute pathname that is the current working
## directory of the calling process.
when defined(posix):
while true:
let res = getcwd(nil, 0)
if isNil(res):
let errCode = ioLastError()
if errCode == EINTR:
continue
else:
return err(errCode)
else:
var buffer = $res
c_free(res)
return ok(buffer)
elif defined(windows):
var bufsize = uint32(MAX_PATH)
var buffer = newWideCString("", int(bufsize))
while true:
let res = getCurrentDirectoryW(bufsize, buffer)
if res == 0'u32:
return err(ioLastError())
elif res > bufsize:
buffer = newWideCString("", int(res))
bufsize = res
else:
return ok(buffer$int(res))
proc setUmask*(mask: int): int {.inline.} =
## Procedure shall set the file mode creation mask of the process to ``mask``
## and return the previous value of the ``mask``.
##
## Note: On Windows this is empty procedure which always returns ``0``.
when defined(windows):
0
else:
int(posix.umask(Mode(mask)))
proc rawCreateDir(dir: string, mode: int = 0o755,
secDescriptor: pointer = nil): IoResult[bool] =
## Attempts to create a directory named ``dir``.
##
## The argument ``mode`` specifies the mode for the new directory.
## It is modified by the process's umask in the usual way: in the absence of
## a default ACL, the mode of the created directory is
## (mode and not(umask) and 0o777). Whether other mode bits are honored for
## the created directory depends on the operating system.
##
## Returns ``true`` if directory was successfully created and ``false`` if
## path ``dir`` is already exists.
when defined(posix):
when defined(solaris):
let existFlags = [EEXIST, ENOSYS]
elif defined(haiku):
let existFlags = [EEXIST, EROFS]
else:
let existFlags = [EEXIST]
while true:
let omask = setUmask(0)
let res = posix.mkdir(cstring(dir), Mode(mode))
discard setUmask(omask)
if res == 0'i32:
return ok(true)
else:
let errCode = ioLastError()
if cint(errCode) in existFlags:
return ok(false)
elif errCode == EINTR:
continue
else:
return err(errCode)
elif defined(windows):
var sa = SECURITY_ATTRIBUTES(
nLength: uint32(sizeof(SECURITY_ATTRIBUTES)),
lpSecurityDescriptor: secDescriptor,
bInheritHandle: 0
)
let res = createDirectoryW(newWideCString(fixPath(dir)), sa)
if res != 0'i32:
ok(true)
else:
let errCode = ioLastError()
if errCode == ERROR_ALREADY_EXISTS:
ok(false)
else:
err(errCode)
proc removeDir*(dir: string): IoResult[void] =
## Deletes a directory, which must be empty.
when defined(posix):
while true:
let res = posix.rmdir(cstring(dir))
if res == 0:
return ok()
else:
let errCode = ioLastError()
if errCode == EINTR:
continue
else:
return err(errCode)
elif defined(windows):
let res = removeDirectoryW(newWideCString(fixPath(dir)))
if res != 0'i32:
ok()
else:
err(ioLastError())
proc removeFile*(path: string): IoResult[void] =
## Deletes a file ``path``.
##
## Procedure will not fail, if file do not exist.
when defined(posix):
if posix.unlink(path) != 0'i32:
let errCode = ioLastError()
if errCode == ENOENT:
ok()
else:
err(errCode)
else:
ok()
elif defined(windows):
if deleteFileW(newWideCString(fixPath(path))) == 0:
let errCode = ioLastError()
if errCode == ERROR_FILE_NOT_FOUND:
ok()
else:
err(errCode)
else:
ok()
proc isFile*(path: string): bool =
## Returns ``true`` if ``path`` exists and is a regular file or symlink.
when defined(posix):
var a: posix.Stat
let res = posix.stat(path, a)
if res == -1:
false
else:
posix.S_ISREG(a.st_mode)
elif defined(windows):
let res = getFileAttributes(newWideCString(fixPath(path)))
if res == INVALID_FILE_ATTRIBUTES:
false
else:
(res and FILE_ATTRIBUTE_DIRECTORY) == 0'u32
proc isDir*(path: string): bool =
## Returns ``true`` if ``path`` exists and is a directory.
when defined(posix):
var a: posix.Stat
let res = posix.stat(path, a)
if res == -1:
false
else:
posix.S_ISDIR(a.st_mode)
elif defined(windows):
let res = getFileAttributes(newWideCString(fixPath(path)))
if res == INVALID_FILE_ATTRIBUTES:
false
else:
(res and FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY
proc getPathItems(path: string, reverse: bool): seq[string] =
var paths: seq[string]
let root = $DirSep
when defined(windows):
let (drive, dpath) = splitDrive(path)
var curpath = dpath
else:
var curpath = path
normPathEnd(curpath, trailingSep = false)
while true:
let curbase = basename(curpath)
let curdir = dirname(curpath)
curpath = curdir
if len(curbase) > 0:
when defined(posix):
if len(curdir) > 0 and curdir != root:
paths.add(curdir & DirSep & curbase)
else:
paths.add(curdir & curbase)
elif defined(windows):
if len(curdir) > 0 and curdir != root:
paths.add(drive & curdir & DirSep & curbase)
else:
paths.add(drive & curdir & curbase)
else:
break
if reverse:
paths.reverse()
paths
proc createPath*(path: string, createMode: int = 0o755,
secDescriptor: pointer = nil): IoResult[void] =
## Creates the full path ``path`` with mode ``createMode``.
##
## Path may contain several subfolders that do not exist yet.
## The full path is created. If this fails, error will be returned.
##
## It does **not** fail if the folder already exists because for
## most usages this does not indicate an error.
let paths = getPathItems(path, true)
for item in paths:
let res = rawCreateDir(item, createMode, secDescriptor)
if res.isErr():
return err(res.error)
ok()
proc toPermissions*(mask: int): Permissions =
## Converts permissions mask's integer to set of ``Permission``.
var res: Permissions
when defined(posix):
if (mask and S_IRUSR) != 0: res.incl(UserRead)
if (mask and S_IWUSR) != 0: res.incl(UserWrite)
if (mask and S_IXUSR) != 0: res.incl(UserExec)
if (mask and S_IRGRP) != 0: res.incl(GroupRead)
if (mask and S_IWGRP) != 0: res.incl(GroupWrite)
if (mask and S_IXGRP) != 0: res.incl(GroupExec)
if (mask and S_IROTH) != 0: res.incl(OtherRead)
if (mask and S_IWOTH) != 0: res.incl(OtherWrite)
if (mask and S_IXOTH) != 0: res.incl(OtherExec)
res
elif defined(windows):
if (mask and 0o400) != 0: res.incl(UserRead)
if (mask and 0o200) != 0: res.incl(UserWrite)
if (mask and 0o100) != 0: res.incl(UserExec)
if (mask and 0o40) != 0: res.incl(GroupRead)
if (mask and 0o20) != 0: res.incl(GroupWrite)
if (mask and 0o10) != 0: res.incl(GroupExec)
if (mask and 0o4) != 0: res.incl(OtherRead)
if (mask and 0o2) != 0: res.incl(OtherWrite)
if (mask and 0o1) != 0: res.incl(OtherExec)
res
proc toInt*(mask: Permissions): int =
## Converts set of ``Permission`` to permissions mask's integer.
var rnum = 0
when defined(windows):
if UserRead in mask:
rnum = rnum or 0o400
if UserWrite in mask:
rnum = rnum or 0o200
if UserExec in mask:
rnum = rnum or 0o100
if GroupRead in mask:
rnum = rnum or 0o40
if GroupWrite in mask:
rnum = rnum or 0o20
if GroupExec in mask:
rnum = rnum or 0o10
if OtherRead in mask:
rnum = rnum or 0o4
if OtherWrite in mask:
rnum = rnum or 0o2
if OtherExec in mask:
rnum = rnum or 0o1
rnum
elif defined(posix):
if UserRead in mask:
rnum = rnum or S_IRUSR
if UserWrite in mask:
rnum = rnum or S_IWUSR
if UserExec in mask:
rnum = rnum or S_IXUSR
if GroupRead in mask:
rnum = rnum or S_IRGRP
if GroupWrite in mask:
rnum = rnum or S_IWGRP
if GroupExec in mask:
rnum = rnum or S_IXGRP
if OtherRead in mask:
rnum = rnum or S_IROTH
if OtherWrite in mask:
rnum = rnum or S_IWOTH
if OtherExec in mask:
rnum = rnum or S_IXOTH
rnum
else:
0o777
proc getPermissions*(pathName: string): IoResult[int] =
## Retreive permissions of file/folder ``pathName`` and return it as integer.
when defined(posix):
var a: posix.Stat
let res = posix.stat(pathName, a)
if res == 0:
ok(int(a.st_mode) and 0o777)
else:
err(ioLastError())
elif defined(windows):
let res = getFileAttributes(newWideCString(fixPath(pathName)))
if res == INVALID_FILE_ATTRIBUTES:
err(ioLastError())
else:
if (res and FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY:
ok(0o555)
else:
ok(0o777)
else:
ok(0o777)
proc getPermissions*(handle: IoHandle): IoResult[int] =
## Retrieve permissions for file descriptor ``handle`` and return it as
## integer.
when defined(posix):
var statbuf: posix.Stat
let res = posix.fstat(cint(handle), statbuf)
if res == 0:
ok(int(statbuf.st_mode) and 0o777)
else:
err(ioLastError())
elif defined(windows):
var info: BY_HANDLE_FILE_INFORMATION
let res = getFileInformationByHandle(uint(handle), info)
if res != 0:
let attr = info.dwFileAttributes
if (attr and FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY:
ok(0o555)
else:
ok(0o777)
else:
err(ioLastError())
else:
ok(0o777)
proc getPermissionsSet*(pathName: string): IoResult[Permissions] =
## Retreive permissions of file/folder ``pathName`` and return set of
## ``Permission`.
let mask = ? getPermissions(pathName)
when defined(windows) or defined(posix):
ok(mask.toPermissions())
else:
ok({UserRead .. OtherExec})
proc getPermissionsSet*(handle: IoHandle): IoResult[Permissions] =
let mask = ? getPermissions(handle)
when defined(windows) or defined(posix):
ok(mask.toPermissions())
else:
ok({UserRead .. OtherExec})
proc setPermissions*(pathName: string, mask: int): IoResult[void] =
## Set permissions for file/folder ``pathame``.
when defined(windows):
let gres = getFileAttributes(newWideCString(fixPath(pathName)))
if gres == INVALID_FILE_ATTRIBUTES:
err(ioLastError())
else:
let nmask =
if (mask and 0o222) == 0:
gres or uint32(FILE_ATTRIBUTE_READONLY)
else:
gres and not(FILE_ATTRIBUTE_READONLY)
let sres = setFileAttributes(newWideCString(fixPath(pathName)),
nmask)
if sres == 0:
err(ioLastError())
else:
ok()
elif defined(posix):
while true:
let omask = setUmask(0)
let res = posix.chmod(pathName, Mode(mask))
discard setUmask(omask)
if res == 0:
return ok()
else:
let errCode = ioLastError()
if errCode == EINTR:
continue
else:
return err(errCode)
proc setPermissions*(handle: IoHandle, mask: int): IoResult[void] =
## Set permissions for handle ``handle``.
when defined(posix):
while true:
let omask = setUmask(0)
let res = posix.fchmod(cint(handle), Mode(mask))
discard setUmask(omask)
if res == 0:
return ok()
else:
let errCode = ioLastError()
if errCode == EINTR:
continue
else:
return err(errCode)
elif defined(windows):
var info: FILE_BASIC_INFO
let infoSize = uint32(sizeof(FILE_BASIC_INFO))
let gres = getFileInformationByHandleEx(uint(handle),
FileBasicInfoClass,
cast[pointer](addr info), infoSize)
if gres == 0:
err(ioLastError())
else:
info.fileAttributes =
if (mask and 0o222) == 0:
info.fileAttributes or uint32(FILE_ATTRIBUTE_READONLY)
else:
info.fileAttributes and not(FILE_ATTRIBUTE_READONLY)
let sres = setFileInformationByHandle(uint(handle),
FileBasicInfoClass,
cast[pointer](addr info), infoSize)
if sres == 0:
err(ioLastError())
else:
ok()
proc setPermissions*(pathName: string, mask: Permissions): IoResult[void] =
## Set permissions for file/folder ``pathame`` using mask ``mask``.
setPermissions(pathName, mask.toInt())
proc setPermissions*(handle: IoHandle, mask: Permissions): IoResult[void] =
## Set permissions for file descriptor ``handle`` using mask ``mask``.
setPermissions(handle, mask.toInt())
proc fileAccessible*(pathName: string, mask: set[AccessFlags]): bool =
## Checks the file ``pathName`` for accessibility according to the bit
## pattern contained in ``mask``.
when defined(posix):
var mode: cint
if AccessFlags.Find in mask:
mode = mode or posix.F_OK
if AccessFlags.Read in mask:
mode = mode or posix.R_OK
if AccessFlags.Write in mask:
mode = mode or posix.W_OK
if AccessFlags.Execute in mask:
mode = mode or posix.X_OK
let res = posix.access(cstring(pathName), mode)
if res == 0:
true
else:
false
elif defined(windows):
let res = getFileAttributes(newWideCString(fixPath(pathName)))
if res == INVALID_FILE_ATTRIBUTES:
return false
if AccessFlags.Write in mask:
if (res and FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY:
return false
else:
return true
return true
proc toString*(mask: Permissions): string =
## Return mask representation as human-readable string in format
## "0xxx (---------)" where `xxx` is numeric representation of permissions.
var rnum = 0
var rstr = "0000 (---------)"
if UserRead in mask:
rstr[6] = 'r'
rnum = rnum or 0o400
if UserWrite in mask:
rstr[7] = 'w'
rnum = rnum or 0o200
if UserExec in mask:
rstr[8] = 'x'
rnum = rnum or 0o100
if GroupRead in mask:
rstr[9] = 'r'
rnum = rnum or 0o40
if GroupWrite in mask:
rstr[10] = 'w'
rnum = rnum or 0o20
if GroupExec in mask:
rstr[11] = 'x'
rnum = rnum or 0o10
if OtherRead in mask:
rstr[12] = 'r'
rnum = rnum or 0o4
if OtherWrite in mask:
rstr[13] = 'w'
rnum = rnum or 0o2
if OtherExec in mask:
rstr[14] = 'x'
rnum = rnum or 0o1
if (rnum and 0o700) != 0:
rstr[1] = ($((rnum shr 6) and 0x07))[0]
if (rnum and 0o70) != 0:
rstr[2] = ($((rnum shr 3) and 0x07))[0]
if (rnum and 0o7) != 0:
rstr[3] = ($(rnum and 0x07))[0]
rstr
proc checkPermissions*(pathName: string, mask: int): bool =
## Checks if the file ``pathName`` permissions is equal to ``mask``.
when defined(windows):
true
elif defined(posix):
var statbuf: posix.Stat
let res = posix.stat(pathName, statbuf)
if res == 0:
(int(statbuf.st_mode) and 0o777) == mask
else:
false
else:
true
proc openFile*(pathName: string, flags: set[OpenFlags],
createMode: int = 0o644,
secDescriptor: pointer = nil): IoResult[IoHandle] =