-
-
Notifications
You must be signed in to change notification settings - Fork 694
/
file.d
3374 lines (2881 loc) · 96.8 KB
/
file.d
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
// Written in the D programming language.
/**
Utilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one _file
at a time. For opening files and manipulating them via handles refer
to module $(LINK2 std_stdio.html,$(D std.stdio)).
Macros:
WIKI = Phobos/StdFile
Copyright: Copyright Digital Mars 2007 - 2011.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB digitalmars.com, Walter Bright),
$(WEB erdani.org, Andrei Alexandrescu),
Jonathan M Davis
Source: $(PHOBOSSRC std/_file.d)
*/
module std.file;
import core.stdc.stdlib, core.stdc.string, core.stdc.errno;
import std.conv;
import std.datetime;
import std.exception;
import std.path;
import std.range.primitives;
import std.traits;
import std.typecons;
import std.typetuple;
import std.internal.cstring;
version (Windows)
{
import core.sys.windows.windows, std.windows.syserror;
}
else version (Posix)
{
import core.sys.posix.dirent, core.sys.posix.fcntl, core.sys.posix.sys.stat,
core.sys.posix.sys.time, core.sys.posix.unistd, core.sys.posix.utime;
}
else
static assert(false, "Module " ~ .stringof ~ " not implemented for this OS.");
version (unittest)
{
@property string deleteme() @safe
{
import std.process : thisProcessID;
static _deleteme = "deleteme.dmd.unittest.pid";
static _first = true;
if(_first)
{
_deleteme = buildPath(tempDir(), _deleteme) ~ to!string(thisProcessID);
_first = false;
}
return _deleteme;
}
version(Android)
{
enum system_directory = "/system/etc";
enum system_file = "/system/etc/hosts";
}
else version(Posix)
{
enum system_directory = "/usr/include";
enum system_file = "/usr/include/assert.h";
}
}
// @@@@ TEMPORARY - THIS SHOULD BE IN THE CORE @@@
// {{{
version (Windows)
{
enum FILE_ATTRIBUTE_REPARSE_POINT = 0x400;
// Required by tempPath():
private extern(Windows) DWORD GetTempPathW(DWORD nBufferLength,
LPWSTR lpBuffer);
// Required by rename():
enum MOVEFILE_REPLACE_EXISTING = 1;
private extern(Windows) DWORD MoveFileExW(LPCWSTR lpExistingFileName,
LPCWSTR lpNewFileName,
DWORD dwFlags);
}
// }}}
/++
Exception thrown for file I/O errors.
+/
class FileException : Exception
{
/++
OS error code.
+/
immutable uint errno;
/++
Constructor which takes an error message.
Params:
name = Name of file for which the error occurred.
msg = Message describing the error.
file = The file where the error occurred.
line = The line where the error occurred.
+/
this(in char[] name, in char[] msg, string file = __FILE__, size_t line = __LINE__) @safe pure
{
if(msg.empty)
super(name.idup, file, line);
else
super(text(name, ": ", msg), file, line);
errno = 0;
}
/++
Constructor which takes the error number ($(LUCKY GetLastError)
in Windows, $(D_PARAM errno) in Posix).
Params:
name = Name of file for which the error occurred.
errno = The error number.
file = The file where the error occurred.
Defaults to $(D __FILE__).
line = The line where the error occurred.
Defaults to $(D __LINE__).
+/
version(Windows) this(in char[] name,
uint errno = .GetLastError(),
string file = __FILE__,
size_t line = __LINE__) @safe
{
this(name, sysErrorString(errno), file, line);
this.errno = errno;
}
else version(Posix) this(in char[] name,
uint errno = .errno,
string file = __FILE__,
size_t line = __LINE__) @trusted
{
auto s = strerror(errno);
this(name, to!string(s), file, line);
this.errno = errno;
}
}
private T cenforce(T)(T condition, lazy const(char)[] name, string file = __FILE__, size_t line = __LINE__)
{
if (!condition)
{
version (Windows)
{
throw new FileException(name, .GetLastError(), file, line);
}
else version (Posix)
{
throw new FileException(name, .errno, file, line);
}
}
return condition;
}
/* **********************************
* Basic File operations.
*/
/********************************************
Read entire contents of file $(D name) and returns it as an untyped
array. If the file size is larger than $(D upTo), only $(D upTo)
bytes are read.
Example:
----
import std.file, std.stdio;
void main()
{
auto bytes = cast(ubyte[]) read("filename", 5);
if (bytes.length == 5)
writefln("The fifth byte of the file is 0x%x", bytes[4]);
}
----
Returns: Untyped array of bytes _read.
Throws: $(D FileException) on error.
*/
void[] read(in char[] name, size_t upTo = size_t.max) @safe
{
import std.algorithm : min;
import std.array : uninitializedArray;
static trustedRef(T)(ref T buf) @trusted
{
return &buf;
}
version(Windows)
{
static trustedCreateFileW(in char[] fileName, DWORD dwDesiredAccess, DWORD dwShareMode,
SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) @trusted
{
return CreateFileW(fileName.tempCStringW(), dwDesiredAccess, dwShareMode,
lpSecurityAttributes, dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
}
static trustedCloseHandle(HANDLE hObject) @trusted
{
return CloseHandle(hObject);
}
static trustedGetFileSize(HANDLE hFile, DWORD *lpFileSizeHigh) @trusted
{
return GetFileSize(hFile, lpFileSizeHigh);
}
static trustedReadFile(HANDLE hFile, void *lpBuffer, DWORD nNumberOfBytesToRead,
DWORD *lpNumberOfBytesRead, OVERLAPPED *lpOverlapped) @trusted
{
return ReadFile(hFile, lpBuffer, nNumberOfBytesToRead,
lpNumberOfBytesRead, lpOverlapped);
}
alias defaults =
TypeTuple!(GENERIC_READ,
FILE_SHARE_READ, (SECURITY_ATTRIBUTES*).init, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
HANDLE.init);
auto h = trustedCreateFileW(name, defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit) cenforce(trustedCloseHandle(h), name);
auto size = trustedGetFileSize(h, null);
cenforce(size != INVALID_FILE_SIZE, name);
size = min(upTo, size);
auto buf = uninitializedArray!(ubyte[])(size);
scope(failure) delete buf;
DWORD numread = void;
cenforce(trustedReadFile(h,buf.ptr, size, trustedRef(numread), null) != 0
&& numread == size, name);
return buf[0 .. size];
}
else version(Posix)
{
import core.memory;
// A few internal configuration parameters {
enum size_t
minInitialAlloc = 1024 * 4,
maxInitialAlloc = size_t.max / 2,
sizeIncrement = 1024 * 16,
maxSlackMemoryAllowed = 1024;
// }
static trustedOpen(in char[] path, int oflag) @trusted
{
return core.sys.posix.fcntl.open(path.tempCString(), oflag);
}
static trustedFstat(int path, stat_t* buf) @trusted
{
return fstat(path, buf);
}
static trustedRead(int fildes, void* buf, size_t nbyte) @trusted
{
return core.sys.posix.unistd.read(fildes, buf, nbyte);
}
static trustedRealloc(void* p, size_t sz, uint ba = 0, const TypeInfo ti = null) @trusted
{
return GC.realloc(p, sz, ba, ti);
}
static trustedPtrAdd(void[] buf, size_t s) @trusted
{
return buf.ptr+s;
}
static trustedPtrSlicing(void* ptr, size_t lb, size_t ub) @trusted
{
return ptr[lb..ub];
}
immutable fd = trustedOpen(name,
core.sys.posix.fcntl.O_RDONLY);
cenforce(fd != -1, name);
scope(exit) core.sys.posix.unistd.close(fd);
stat_t statbuf = void;
cenforce(trustedFstat(fd, trustedRef(statbuf)) == 0, name);
immutable initialAlloc = to!size_t(statbuf.st_size
? min(statbuf.st_size + 1, maxInitialAlloc)
: minInitialAlloc);
void[] result = uninitializedArray!(ubyte[])(initialAlloc);
scope(failure) delete result;
size_t size = 0;
for (;;)
{
immutable actual = trustedRead(fd, trustedPtrAdd(result, size),
min(result.length, upTo) - size);
cenforce(actual != -1, name);
if (actual == 0) break;
size += actual;
if (size < result.length) continue;
immutable newAlloc = size + sizeIncrement;
result = trustedPtrSlicing(trustedRealloc(result.ptr, newAlloc, GC.BlkAttr.NO_SCAN),
0, newAlloc);
}
return result.length - size >= maxSlackMemoryAllowed
? trustedPtrSlicing(trustedRealloc(result.ptr, size, GC.BlkAttr.NO_SCAN), 0, size)
: result[0 .. size];
}
}
@safe unittest
{
write(deleteme, "1234");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
assert(read(deleteme, 2) == "12");
assert(read(deleteme) == "1234");
}
version (linux) @safe unittest
{
// A file with "zero" length that doesn't have 0 length at all
auto s = std.file.readText("/proc/sys/kernel/osrelease");
assert(s.length > 0);
//writefln("'%s'", s);
}
/********************************************
Read and validates (using $(XREF utf, validate)) a text file. $(D S)
can be a type of array of characters of any width and constancy. No
width conversion is performed; if the width of the characters in file
$(D name) is different from the width of elements of $(D S),
validation will fail.
Returns: Array of characters read.
Throws: $(D FileException) on file error, $(D UTFException) on UTF
decoding error.
Example:
----
enforce(system("echo abc>deleteme") == 0);
scope(exit) remove("deleteme");
enforce(chomp(readText("deleteme")) == "abc");
----
*/
S readText(S = string)(in char[] name) @safe if (isSomeString!S)
{
import std.utf : validate;
static auto trustedCast(void[] buf) @trusted { return cast(S)buf; }
auto result = trustedCast(read(name));
validate(result);
return result;
}
@safe unittest
{
import std.string;
write(deleteme, "abc\n");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
enforce(chomp(readText(deleteme)) == "abc");
}
/*********************************************
Write $(D buffer) to file $(D name).
Throws: $(D FileException) on error.
Example:
----
import std.file;
void main()
{
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write("filename", a);
assert(cast(int[]) read("filename") == a);
}
----
*/
void write(in char[] name, const void[] buffer) @trusted
{
version(Windows)
{
alias defaults =
TypeTuple!(GENERIC_WRITE, 0, null, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
HANDLE.init);
auto h = CreateFileW(name.tempCStringW(), defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit) cenforce(CloseHandle(h), name);
DWORD numwritten;
cenforce(WriteFile(h, buffer.ptr, to!DWORD(buffer.length), &numwritten, null) != 0
&& buffer.length == numwritten,
name);
}
else version(Posix)
return writeImpl(name, buffer, O_CREAT | O_WRONLY | O_TRUNC);
}
/*********************************************
Appends $(D buffer) to file $(D name).
Throws: $(D FileException) on error.
Example:
----
import std.file;
void main()
{
int[] a = [ 0, 1, 1, 2, 3, 5, 8 ];
write("filename", a);
int[] b = [ 13, 21 ];
append("filename", b);
assert(cast(int[]) read("filename") == a ~ b);
}
----
*/
void append(in char[] name, in void[] buffer) @trusted
{
version(Windows)
{
alias defaults =
TypeTuple!(GENERIC_WRITE,0,null,OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,HANDLE.init);
auto h = CreateFileW(name.tempCStringW(), defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit) cenforce(CloseHandle(h), name);
DWORD numwritten;
cenforce(SetFilePointer(h, 0, null, FILE_END) != INVALID_SET_FILE_POINTER
&& WriteFile(h,buffer.ptr,to!DWORD(buffer.length),&numwritten,null) != 0
&& buffer.length == numwritten,
name);
}
else version(Posix)
return writeImpl(name, buffer, O_APPEND | O_WRONLY | O_CREAT);
}
// Posix implementation helper for write and append
version(Posix) private void writeImpl(in char[] name,
in void[] buffer, in uint mode) @trusted
{
immutable fd = core.sys.posix.fcntl.open(name.tempCString(),
mode, octal!666);
cenforce(fd != -1, name);
{
scope(failure) core.sys.posix.unistd.close(fd);
immutable size = buffer.length;
cenforce(
core.sys.posix.unistd.write(fd, buffer.ptr, size) == size,
name);
}
cenforce(core.sys.posix.unistd.close(fd) == 0, name);
}
/***************************************************
* Rename file $(D from) to $(D to).
* If the target file exists, it is overwritten.
* Throws: $(D FileException) on error.
*/
void rename(in char[] from, in char[] to) @trusted
{
version(Windows)
{
enforce(MoveFileExW(from.tempCStringW(), to.tempCStringW(), MOVEFILE_REPLACE_EXISTING),
new FileException(
text("Attempting to rename file ", from, " to ",
to)));
}
else version(Posix)
{
import core.stdc.stdio;
cenforce(core.stdc.stdio.rename(from.tempCString(), to.tempCString()) == 0, to);
}
}
@safe unittest
{
auto t1 = deleteme, t2 = deleteme~"2";
scope(exit) foreach (t; [t1, t2]) if (t.exists) t.remove();
write(t1, "1");
rename(t1, t2);
assert(readText(t2) == "1");
write(t1, "2");
rename(t1, t2);
assert(readText(t2) == "2");
}
/***************************************************
Delete file $(D name).
Throws: $(D FileException) on error.
*/
void remove(in char[] name) @trusted
{
version(Windows)
{
cenforce(DeleteFileW(name.tempCStringW()), name);
}
else version(Posix)
{
import core.stdc.stdio;
cenforce(core.stdc.stdio.remove(name.tempCString()) == 0,
"Failed to remove file " ~ name);
}
}
version(Windows) private WIN32_FILE_ATTRIBUTE_DATA getFileAttributesWin(in char[] name) @trusted
{
WIN32_FILE_ATTRIBUTE_DATA fad;
enforce(GetFileAttributesExW(name.tempCStringW(), GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, &fad), new FileException(name.idup));
return fad;
}
version(Windows) private ulong makeUlong(DWORD dwLow, DWORD dwHigh) @safe pure nothrow @nogc
{
ULARGE_INTEGER li;
li.LowPart = dwLow;
li.HighPart = dwHigh;
return li.QuadPart;
}
/***************************************************
Get size of file $(D name) in bytes.
Throws: $(D FileException) on error (e.g., file not found).
*/
ulong getSize(in char[] name) @safe
{
version(Windows)
{
with (getFileAttributesWin(name))
return makeUlong(nFileSizeLow, nFileSizeHigh);
}
else version(Posix)
{
static auto trustedStat(in char[] path, stat_t* buf) @trusted
{
return stat(path.tempCString(), buf);
}
static stat_t* ptrOfLocalVariable(ref stat_t buf) @trusted
{
return &buf;
}
stat_t statbuf = void;
cenforce(trustedStat(name, ptrOfLocalVariable(statbuf)) == 0, name);
return statbuf.st_size;
}
}
@safe unittest
{
// create a file of size 1
write(deleteme, "a");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
assert(getSize(deleteme) == 1);
// create a file of size 3
write(deleteme, "abc");
assert(getSize(deleteme) == 3);
}
/++
Get the access and modified times of file or folder $(D name).
Params:
name = File/Folder name to get times for.
accessTime = Time the file/folder was last accessed.
modificationTime = Time the file/folder was last modified.
Throws:
$(D FileException) on error.
+/
void getTimes(in char[] name,
out SysTime accessTime,
out SysTime modificationTime) @safe
{
version(Windows)
{
with (getFileAttributesWin(name))
{
accessTime = FILETIMEToSysTime(&ftLastAccessTime);
modificationTime = FILETIMEToSysTime(&ftLastWriteTime);
}
}
else version(Posix)
{
static auto trustedStat(in char[] path, ref stat_t buf) @trusted
{
return stat(path.tempCString(), &buf);
}
stat_t statbuf = void;
cenforce(trustedStat(name, statbuf) == 0, name);
accessTime = SysTime(unixTimeToStdTime(statbuf.st_atime));
modificationTime = SysTime(unixTimeToStdTime(statbuf.st_mtime));
}
}
unittest
{
import std.stdio : writefln;
auto currTime = Clock.currTime();
write(deleteme, "a");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
SysTime accessTime1 = void;
SysTime modificationTime1 = void;
getTimes(deleteme, accessTime1, modificationTime1);
enum leeway = dur!"seconds"(5);
{
auto diffa = accessTime1 - currTime;
auto diffm = modificationTime1 - currTime;
scope(failure) writefln("[%s] [%s] [%s] [%s] [%s]", accessTime1, modificationTime1, currTime, diffa, diffm);
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
version(fullFileTests)
{
import core.thread;
enum sleepTime = dur!"seconds"(2);
Thread.sleep(sleepTime);
currTime = Clock.currTime();
write(deleteme, "b");
SysTime accessTime2 = void;
SysTime modificationTime2 = void;
getTimes(deleteme, accessTime2, modificationTime2);
{
auto diffa = accessTime2 - currTime;
auto diffm = modificationTime2 - currTime;
scope(failure) writefln("[%s] [%s] [%s] [%s] [%s]", accessTime2, modificationTime2, currTime, diffa, diffm);
//There is no guarantee that the access time will be updated.
assert(abs(diffa) <= leeway + sleepTime);
assert(abs(diffm) <= leeway);
}
assert(accessTime1 <= accessTime2);
assert(modificationTime1 <= modificationTime2);
}
}
/++
$(BLUE This function is Windows-Only.)
Get creation/access/modified times of file $(D name).
This is the same as $(D getTimes) except that it also gives you the file
creation time - which isn't possible on Posix systems.
Params:
name = File name to get times for.
fileCreationTime = Time the file was created.
fileAccessTime = Time the file was last accessed.
fileModificationTime = Time the file was last modified.
Throws:
$(D FileException) on error.
+/
version(StdDdoc) void getTimesWin(in char[] name,
out SysTime fileCreationTime,
out SysTime fileAccessTime,
out SysTime fileModificationTime) @safe;
else version(Windows) void getTimesWin(in char[] name,
out SysTime fileCreationTime,
out SysTime fileAccessTime,
out SysTime fileModificationTime) @safe
{
with (getFileAttributesWin(name))
{
fileCreationTime = std.datetime.FILETIMEToSysTime(&ftCreationTime);
fileAccessTime = std.datetime.FILETIMEToSysTime(&ftLastAccessTime);
fileModificationTime = std.datetime.FILETIMEToSysTime(&ftLastWriteTime);
}
}
version(Windows) unittest
{
import std.stdio : writefln;
auto currTime = Clock.currTime();
write(deleteme, "a");
scope(exit) { assert(exists(deleteme)); remove(deleteme); }
SysTime creationTime1 = void;
SysTime accessTime1 = void;
SysTime modificationTime1 = void;
getTimesWin(deleteme, creationTime1, accessTime1, modificationTime1);
enum leeway = dur!"seconds"(5);
{
auto diffc = creationTime1 - currTime;
auto diffa = accessTime1 - currTime;
auto diffm = modificationTime1 - currTime;
scope(failure)
{
writefln("[%s] [%s] [%s] [%s] [%s] [%s] [%s]",
creationTime1, accessTime1, modificationTime1, currTime, diffc, diffa, diffm);
}
// Deleting and recreating a file doesn't seem to always reset the "file creation time"
//assert(abs(diffc) <= leeway);
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
version(fullFileTests)
{
import core.thread;
Thread.sleep(dur!"seconds"(2));
currTime = Clock.currTime();
write(deleteme, "b");
SysTime creationTime2 = void;
SysTime accessTime2 = void;
SysTime modificationTime2 = void;
getTimesWin(deleteme, creationTime2, accessTime2, modificationTime2);
{
auto diffa = accessTime2 - currTime;
auto diffm = modificationTime2 - currTime;
scope(failure)
{
writefln("[%s] [%s] [%s] [%s] [%s]",
accessTime2, modificationTime2, currTime, diffa, diffm);
}
assert(abs(diffa) <= leeway);
assert(abs(diffm) <= leeway);
}
assert(creationTime1 == creationTime2);
assert(accessTime1 <= accessTime2);
assert(modificationTime1 <= modificationTime2);
}
}
/++
Set access/modified times of file or folder $(D name).
Params:
name = File/Folder name to get times for.
accessTime = Time the file/folder was last accessed.
modificationTime = Time the file/folder was last modified.
Throws:
$(D FileException) on error.
+/
void setTimes(in char[] name,
SysTime accessTime,
SysTime modificationTime) @safe
{
version(Windows)
{
static auto trustedCreateFileW(in char[] fileName, DWORD dwDesiredAccess, DWORD dwShareMode,
SECURITY_ATTRIBUTES *lpSecurityAttributes, DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) @trusted
{
return CreateFileW(fileName.tempCStringW(), dwDesiredAccess, dwShareMode,
lpSecurityAttributes, dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
}
static auto trustedCloseHandle(HANDLE hObject) @trusted
{
return CloseHandle(hObject);
}
static auto trustedSetFileTime(HANDLE hFile, in FILETIME *lpCreationTime,
in ref FILETIME lpLastAccessTime, in ref FILETIME lpLastWriteTime) @trusted
{
return SetFileTime(hFile, lpCreationTime, &lpLastAccessTime, &lpLastWriteTime);
}
const ta = SysTimeToFILETIME(accessTime);
const tm = SysTimeToFILETIME(modificationTime);
alias defaults =
TypeTuple!(GENERIC_WRITE,
0,
null,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL |
FILE_ATTRIBUTE_DIRECTORY |
FILE_FLAG_BACKUP_SEMANTICS,
HANDLE.init);
auto h = trustedCreateFileW(name, defaults);
cenforce(h != INVALID_HANDLE_VALUE, name);
scope(exit)
cenforce(trustedCloseHandle(h), name);
cenforce(trustedSetFileTime(h, null, ta, tm), name);
}
else version(Posix)
{
static auto trustedUtimes(in char[] path, const ref timeval[2] times) @trusted
{
return utimes(path.tempCString(), times);
}
timeval[2] t = void;
t[0] = accessTime.toTimeVal();
t[1] = modificationTime.toTimeVal();
cenforce(trustedUtimes(name, t) == 0, name);
}
}
unittest
{
import std.stdio : File;
string newdir = deleteme ~ r".dir";
string dir = newdir ~ r"/a/b/c";
string file = dir ~ "/file";
if (!exists(dir)) mkdirRecurse(dir);
{ auto f = File(file, "w"); }
foreach (path; [file, dir]) // test file and dir
{
SysTime atime = SysTime(DateTime(2010, 10, 4, 0, 0, 30));
SysTime mtime = SysTime(DateTime(2011, 10, 4, 0, 0, 30));
setTimes(path, atime, mtime);
SysTime atime_res;
SysTime mtime_res;
getTimes(path, atime_res, mtime_res);
assert(atime == atime_res);
assert(mtime == mtime_res);
}
rmdirRecurse(newdir);
}
/++
Returns the time that the given file was last modified.
Throws:
$(D FileException) if the given file does not exist.
+/
SysTime timeLastModified(in char[] name) @safe
{
version(Windows)
{
SysTime dummy;
SysTime ftm;
getTimesWin(name, dummy, dummy, ftm);
return ftm;
}
else version(Posix)
{
static auto trustedStat(in char[] path, ref stat_t buf) @trusted
{
return stat(path.tempCString(), &buf);
}
stat_t statbuf = void;
cenforce(trustedStat(name, statbuf) == 0, name);
return SysTime(unixTimeToStdTime(statbuf.st_mtime));
}
}
/++
Returns the time that the given file was last modified. If the
file does not exist, returns $(D returnIfMissing).
A frequent usage pattern occurs in build automation tools such as
$(WEB gnu.org/software/make, make) or $(WEB
en.wikipedia.org/wiki/Apache_Ant, ant). To check whether file $(D
target) must be rebuilt from file $(D source) (i.e., $(D target) is
older than $(D source) or does not exist), use the comparison
below. The code throws a $(D FileException) if $(D source) does not
exist (as it should). On the other hand, the $(D SysTime.min) default
makes a non-existing $(D target) seem infinitely old so the test
correctly prompts building it.
Params:
name = The name of the file to get the modification time for.
returnIfMissing = The time to return if the given file does not exist.
Examples:
--------------------
if(timeLastModified(source) >= timeLastModified(target, SysTime.min))
{
// must (re)build
}
else
{
// target is up-to-date
}
--------------------
+/
SysTime timeLastModified(in char[] name, SysTime returnIfMissing) @safe
{
version(Windows)
{
if(!exists(name))
return returnIfMissing;
SysTime dummy;
SysTime ftm;
getTimesWin(name, dummy, dummy, ftm);
return ftm;
}
else version(Posix)
{
static auto trustedStat(in char[] path, ref stat_t buf) @trusted
{
return stat(path.tempCString(), &buf);
}
stat_t statbuf = void;
return trustedStat(name, statbuf) != 0 ?
returnIfMissing :
SysTime(unixTimeToStdTime(statbuf.st_mtime));
}
}
unittest
{
//std.process.system("echo a > deleteme") == 0 || assert(false);
if(exists(deleteme))
remove(deleteme);
write(deleteme, "a\n");
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
// assert(lastModified("deleteme") >
// lastModified("this file does not exist", SysTime.min));
//assert(lastModified("deleteme") > lastModified(__FILE__));
}
/++
Returns whether the given file (or directory) exists.
+/
bool exists(in char[] name) @trusted nothrow @nogc
{
version(Windows)
{
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/
// fileio/base/getfileattributes.asp
return GetFileAttributesW(name.tempCStringW()) != 0xFFFFFFFF;
}
else version(Posix)
{
/*
The reason why we use stat (and not access) here is
the quirky behavior of access for SUID programs: if
we used access, a file may not appear to "exist",
despite that the program would be able to open it
just fine. The behavior in question is described as
follows in the access man page:
> The check is done using the calling process's real
> UID and GID, rather than the effective IDs as is
> done when actually attempting an operation (e.g.,
> open(2)) on the file. This allows set-user-ID