1 /** 2 * File stuff 3 * 4 * License: 5 * This Source Code Form is subject to the terms of 6 * the Mozilla Public License, v. 2.0. If a copy of 7 * the MPL was not distributed with this file, You 8 * can obtain one at http://mozilla.org/MPL/2.0/. 9 * 10 * Authors: 11 * Vladimir Panteleev <ae@cy.md> 12 */ 13 14 module ae.sys.file; 15 16 import core.stdc.wchar_; 17 import core.thread; 18 19 import std.array; 20 import std.conv; 21 import std.file; 22 import std.path; 23 import std.range.primitives; 24 import std.stdio : File; 25 import std.string; 26 import std.typecons; 27 import std.utf; 28 29 import ae.sys.cmd : getCurrentThreadID; 30 import ae.utils.path; 31 32 public import std.typecons : No, Yes; 33 34 deprecated alias wcscmp = core.stdc.wchar_.wcscmp; 35 deprecated alias wcslen = core.stdc.wchar_.wcslen; 36 37 version(Windows) import ae.sys.windows.imports; 38 39 // ************************************************************************ 40 41 version (Windows) 42 { 43 // Work around std.file overload 44 mixin(importWin32!(q{winnt}, null, q{FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT})); 45 } 46 version (Posix) 47 { 48 private import core.stdc.errno; 49 private import core.sys.posix.dirent; 50 private import core.stdc.string; 51 } 52 53 // ************************************************************************ 54 55 deprecated string[] fastListDir(bool recursive = false, bool symlinks=false)(string pathname, string pattern = null) 56 { 57 string[] result; 58 59 listDir!((e) { 60 static if (!symlinks) 61 { 62 // Note: shouldn't this just skip recursion? 63 if (e.isSymlink) 64 return; 65 } 66 67 if (pattern && !globMatch(e.baseName, pattern)) 68 return; 69 70 static if (recursive) 71 { 72 if (e.entryIsDir) 73 { 74 // Note: why exclude directories from results? 75 e.recurse(); 76 return; 77 } 78 } 79 80 result ~= e.fullName; 81 })(pathname); 82 return result; 83 } 84 85 // ************************************************************************ 86 87 version (Windows) 88 { 89 mixin(importWin32!(q{winnt}, null, q{WCHAR})); 90 mixin(importWin32!(q{winbase}, null, q{WIN32_FIND_DATAW})); 91 } 92 93 /// The OS's "native" filesystem character type (private in Phobos). 94 version (Windows) 95 alias FSChar = WCHAR; 96 else version (Posix) 97 alias FSChar = char; 98 else 99 static assert(0); 100 101 /// Reads a time field from a stat_t with full precision (private in Phobos). 102 SysTime statTimeToStdTime(string which)(ref const stat_t statbuf) 103 { 104 auto unixTime = mixin(`statbuf.st_` ~ which ~ `time`); 105 auto stdTime = unixTimeToStdTime(unixTime); 106 107 static if (is(typeof(mixin(`statbuf.st_` ~ which ~ `tim`)))) 108 stdTime += mixin(`statbuf.st_` ~ which ~ `tim.tv_nsec`) / 100; 109 else 110 static if (is(typeof(mixin(`statbuf.st_` ~ which ~ `timensec`)))) 111 stdTime += mixin(`statbuf.st_` ~ which ~ `timensec`) / 100; 112 else 113 static if (is(typeof(mixin(`statbuf.st_` ~ which ~ `time_nsec`)))) 114 stdTime += mixin(`statbuf.st_` ~ which ~ `time_nsec`) / 100; 115 else 116 static if (is(typeof(mixin(`statbuf.__st_` ~ which ~ `timensec`)))) 117 stdTime += mixin(`statbuf.__st_` ~ which ~ `timensec`) / 100; 118 119 return SysTime(stdTime); 120 } 121 122 version (OSX) 123 version = Darwin; 124 else version (iOS) 125 version = Darwin; 126 else version (TVOS) 127 version = Darwin; 128 else version (WatchOS) 129 version = Darwin; 130 131 private 132 version (Posix) 133 { 134 // TODO: upstream into Druntime 135 extern (C) 136 { 137 int dirfd(DIR *dirp) pure nothrow @nogc; 138 int openat(int fd, const char *path, int oflag, ...) nothrow @nogc; 139 140 version (Darwin) 141 { 142 pragma(mangle, "fstatat$INODE64") 143 int fstatat(int fd, const char *path, stat_t *buf, int flag) nothrow @nogc; 144 145 pragma(mangle, "fdopendir$INODE64") 146 DIR *fdopendir(int fd) nothrow @nogc; 147 } 148 else 149 { 150 int fstatat(int fd, const(char)* path, stat_t* buf, int flag) nothrow @nogc; 151 DIR *fdopendir(int fd) nothrow @nogc; 152 } 153 } 154 version (linux) 155 { 156 enum AT_SYMLINK_NOFOLLOW = 0x100; 157 enum O_DIRECTORY = 0x10000; 158 } 159 version (Darwin) 160 { 161 enum AT_SYMLINK_NOFOLLOW = 0x20; 162 enum O_DIRECTORY = 0x100000; 163 } 164 version (FreeBSD) 165 { 166 enum AT_SYMLINK_NOFOLLOW = 0x200; 167 enum O_DIRECTORY = 0x20000; 168 } 169 } 170 171 import ae.utils.range : nullTerminated; 172 173 // https://issues.dlang.org/show_bug.cgi?id=7016 174 version (Windows) static import ae.sys.windows.misc; 175 176 /** 177 Fast templated directory iterator 178 179 Example: 180 --- 181 string[] entries; 182 listDir!((e) { 183 entries ~= e.fullName.relPath(tmpDir); 184 if (e.entryIsDir) 185 e.recurse(); 186 })(tmpDir); 187 --- 188 189 If called with `Yes.includeRoot`, then the callback is 190 first called with the argument, even if it's not a directory. 191 */ 192 template listDir(alias handler, Flag!q{includeRoot} includeRoot = No.includeRoot) 193 { 194 private: // (This is an eponymous template, so this is to aid documentation generators.) 195 /*non-static*/ struct Context 196 { 197 // Tether to handler alias context 198 void callHandler(Entry* e) { handler(e); } 199 200 bool timeToStop = false; 201 202 FSChar[] pathBuf; 203 } 204 205 /// A pointer to this type will be passed to the `listDir` predicate. 206 public static struct Entry 207 { 208 version (Posix) 209 { 210 private const(char)* name; /// Name relative to `dirFD`. 211 dirent* ent; /// POSIX `dirent`. May be null with `Yes.includeRoot`. 212 213 private stat_t[enumLength!StatTarget] statBuf; 214 215 /// Result of `stat` call. 216 /// Other values are the same as `errno`. 217 enum StatResult : int 218 { 219 noInfo = 0, /// Not called yet. 220 statOK = int.max, /// All OK 221 unknownError = int.min, /// `errno` returned 0 or `int.max` 222 } 223 224 int dirFD; /// POSIX directory file descriptor. 225 } 226 version (Windows) 227 { 228 WIN32_FIND_DATAW findData; /// Windows `WIN32_FIND_DATAW`. 229 } 230 231 // Cached values. 232 // Cleared (memset to 0) for every directory entry. 233 struct Data 234 { 235 const(FSChar)[] baseNameFS; 236 string baseName; 237 string fullName; 238 size_t pathTailPos; 239 240 version (Posix) 241 { 242 StatResult[enumLength!StatTarget] statResult; 243 } 244 } 245 Data data; 246 247 // Recursion 248 249 Entry* parent; /// 250 private Context* context; 251 252 /// Request recursion on the current `entry`. 253 version (Posix) 254 { 255 void recurse() 256 { 257 import core.sys.posix.fcntl; 258 int flags = O_RDONLY; 259 static if (is(typeof(O_DIRECTORY))) 260 flags |= O_DIRECTORY; 261 auto fd = openat(dirFD, this.name, flags); 262 errnoEnforce(fd >= 0, 263 "Failed to open %s as subdirectory of directory %s" 264 .format(this.baseNameFS, this.parent.fullName)); 265 auto subdir = fdopendir(fd); 266 errnoEnforce(subdir, 267 "Failed to open subdirectory %s of directory %s as directory" 268 .format(this.baseNameFS, this.parent.fullName)); 269 scan(subdir, fd, &this); 270 } 271 } 272 else 273 version (Windows) 274 { 275 void recurse() 276 { 277 needFullPath(); 278 appendString(context.pathBuf, 279 data.pathTailPos, "\\*.*\0"w); 280 scan(&this); 281 } 282 } 283 284 /// Stop iteration. 285 void stop() { context.timeToStop = true; } 286 287 // Name 288 289 /// Returns a pointer to the base file name, as a 290 /// null-terminated string, in the operating system's 291 /// character type. Fastest. 292 const(FSChar)* baseNameFSPtr() pure nothrow @nogc 293 { 294 version (Posix) return name; 295 version (Windows) return findData.cFileName.ptr; 296 } 297 298 // Bounded variant of std.string.fromStringz for static arrays. 299 private static T[] fromStringz(T, size_t n)(ref T[n] buf) 300 { 301 foreach (i, c; buf) 302 if (!c) 303 return buf[0 .. i]; 304 // This should only happen in case of an OS / libc bug. 305 assert(false, "File name buffer is not null-terminated"); 306 } 307 308 /// Returns the base file name, as a D character array, in the 309 /// operating system's character type. Fast. 310 const(FSChar)[] baseNameFS() pure nothrow @nogc 311 { 312 if (!data.baseNameFS) 313 { 314 version (Posix) data.baseNameFS = .fromStringz(name); 315 version (Windows) data.baseNameFS = fromStringz(findData.cFileName); 316 } 317 return data.baseNameFS; 318 } 319 320 /// Returns the base file name as a D string. Allocates. 321 string baseName() // allocates 322 { 323 if (!data.baseName) 324 data.baseName = baseNameFS.to!string; 325 return data.baseName; 326 } 327 328 private void needFullPath() nothrow @nogc 329 { 330 if (!data.pathTailPos) 331 { 332 version (Posix) 333 parent.needFullPath(); 334 version (Windows) 335 { 336 // directory separator was added during recursion 337 auto startPos = parent.data.pathTailPos + 1; 338 } 339 version (Posix) 340 { 341 immutable FSChar[] separator = "/"; 342 auto startPos = appendString(context.pathBuf, 343 parent.data.pathTailPos, separator); 344 } 345 data.pathTailPos = appendString(context.pathBuf, 346 startPos, 347 baseNameFSPtr.nullTerminated 348 ); 349 } 350 } 351 352 /// Returns the full file name, as a D character array, in the 353 /// operating system's character type. Fast. 354 const(FSChar)[] fullNameFS() nothrow @nogc // fast 355 { 356 needFullPath(); 357 return context.pathBuf[0 .. data.pathTailPos]; 358 } 359 360 /// Returns the full file name as a D string. Allocates. 361 string fullName() // allocates 362 { 363 if (!data.fullName) 364 data.fullName = fullNameFS.to!string; 365 return data.fullName; 366 } 367 368 // Attributes 369 370 version (Posix) 371 { 372 /// We can stat two different things on POSIX: the directory entry itself, 373 /// or the link target (if the directory entry is a symbolic link). 374 enum StatTarget 375 { 376 dirEntry, /// do not dereference (lstat) 377 linkTarget, /// dereference 378 } 379 380 private bool tryStat(StatTarget target)() nothrow @nogc 381 { 382 if (data.statResult[target] == StatResult.noInfo) 383 { 384 // If we already did the other kind of stat, can we reuse its result? 385 if (data.statResult[1 - target] != StatResult.noInfo) 386 { 387 // Yes, if we know this isn't a link from the directory entry. 388 static if (__traits(compiles, ent.d_type)) 389 if (ent && ent.d_type != DT_UNKNOWN && ent.d_type != DT_LNK) 390 goto reuse; 391 // Yes, if we already found out this isn't a link from an lstat call. 392 static if (target == StatTarget.linkTarget) 393 if (data.statResult[StatTarget.dirEntry] == StatResult.statOK 394 && (statBuf[StatTarget.dirEntry].st_mode & S_IFMT) != S_IFLNK) 395 goto reuse; 396 } 397 398 if (false) 399 { 400 reuse: 401 statBuf[target] = statBuf[1 - target]; 402 data.statResult[target] = data.statResult[1 - target]; 403 } 404 else 405 { 406 int flags = target == StatTarget.dirEntry ? AT_SYMLINK_NOFOLLOW : 0; 407 auto res = fstatat(dirFD, name, &statBuf[target], flags); 408 if (res) 409 { 410 auto error = errno; 411 data.statResult[target] = cast(StatResult)error; 412 if (error == StatResult.noInfo || error == StatResult.statOK) 413 data.statResult[target] = StatResult.unknownError; // unknown error? 414 } 415 else 416 data.statResult[target] = StatResult.statOK; // no error 417 } 418 } 419 return data.statResult[target] == StatResult.statOK; 420 } 421 422 private ErrnoException statError(StatTarget target)() 423 { 424 errno = data.statResult[target]; 425 return new ErrnoException("Failed to stat " ~ 426 (target == StatTarget.linkTarget ? "link target" : "directory entry") ~ 427 ": " ~ fullName); 428 } 429 430 /// Return the result of `stat` / `lstat` (depending on `target`) 431 /// for this `Entry`, performing it first if necessary. 432 stat_t* needStat(StatTarget target)() 433 { 434 if (!tryStat!target) 435 throw statError!target(); 436 return &statBuf[target]; 437 } 438 439 // Check if this is an object of the given type. 440 private bool deIsType(typeof(DT_REG) dType, typeof(S_IFREG) statType) 441 { 442 static if (__traits(compiles, ent.d_type)) 443 if (ent && ent.d_type != DT_UNKNOWN) 444 return ent.d_type == dType; 445 446 return (needStat!(StatTarget.dirEntry)().st_mode & S_IFMT) == statType; 447 } 448 449 /// Returns true if this is a symlink. 450 @property bool isSymlink() 451 { 452 return deIsType(DT_LNK, S_IFLNK); 453 } 454 455 /// Returns true if this is a directory. 456 /// You probably want to use this one to decide whether to recurse. 457 @property bool entryIsDir() 458 { 459 return deIsType(DT_DIR, S_IFDIR); 460 } 461 462 // Check if this is an object of the given type, or a link pointing to one. 463 private bool ltIsType(typeof(DT_REG) dType, typeof(S_IFREG) statType) 464 { 465 static if (__traits(compiles, ent.d_type)) 466 if (ent && ent.d_type != DT_UNKNOWN && ent.d_type != DT_LNK) 467 return ent.d_type == dType; 468 469 if (tryStat!(StatTarget.linkTarget)()) 470 return (statBuf[StatTarget.linkTarget].st_mode & S_IFMT) == statType; 471 472 if (isSymlink()) // broken symlink? 473 return false; // a broken symlink does not point at anything. 474 475 throw statError!(StatTarget.linkTarget)(); 476 } 477 478 /// Returns true if this is a file, or a link pointing to one. 479 @property bool isFile() 480 { 481 return ltIsType(DT_REG, S_IFREG); 482 } 483 484 /// Returns true if this is a directory, or a link pointing to one. 485 @property bool isDir() 486 { 487 return ltIsType(DT_DIR, S_IFDIR); 488 } 489 490 /// Returns the raw POSIX attributes of this directory entry, 491 /// or the link target if this directory entry is a symlink. 492 @property uint attributes() 493 { 494 return needStat!(StatTarget.linkTarget)().st_mode; 495 } 496 497 /// Returns the raw POSIX attributes of this directory entry. 498 @property uint linkAttributes() 499 { 500 return needStat!(StatTarget.dirEntry)().st_mode; 501 } 502 503 // Other attributes 504 505 /// Returns the "c" time of this directory entry, 506 /// or the link target if this directory entry is a symlink. 507 @property SysTime timeStatusChanged() 508 { 509 return statTimeToStdTime!"c"(*needStat!(StatTarget.linkTarget)()); 510 } 511 512 /// Returns the "a" time of this directory entry, 513 /// or the link target if this directory entry is a symlink. 514 @property SysTime timeLastAccessed() 515 { 516 return statTimeToStdTime!"a"(*needStat!(StatTarget.linkTarget)()); 517 } 518 519 /// Returns the "m" time of this directory entry, 520 /// or the link target if this directory entry is a symlink. 521 @property SysTime timeLastModified() 522 { 523 return statTimeToStdTime!"m"(*needStat!(StatTarget.linkTarget)()); 524 } 525 526 /// Returns the "birth" time of this directory entry, 527 /// or the link target if this directory entry is a symlink. 528 static if (is(typeof(&statTimeToStdTime!"birth"))) 529 @property SysTime timeCreated() 530 { 531 return statTimeToStdTime!"birth"(*needStat!(StatTarget.linkTarget)()); 532 } 533 534 /// Returns the size in bytes of this directory entry, 535 /// or the link target if this directory entry is a symlink. 536 @property ulong size() 537 { 538 return needStat!(StatTarget.linkTarget)().st_size; 539 } 540 541 /// Returns the inode number of this directory entry, 542 /// or the link target if this directory entry is a symlink. 543 @property ulong fileID() 544 { 545 static if (__traits(compiles, ent.d_ino)) 546 if (ent) 547 return ent.d_ino; 548 return needStat!(StatTarget.linkTarget)().st_ino; 549 } 550 } 551 552 version (Windows) 553 { 554 /// Returns true if this is a directory, or a reparse point pointing to one. 555 @property bool isDir() const pure nothrow 556 { 557 return (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; 558 } 559 560 /// Returns true if this is a file, or a reparse point pointing to one. 561 @property bool isFile() const pure nothrow 562 { 563 return !isDir; 564 } 565 566 /// Returns true if this is a reparse point. 567 @property bool isSymlink() const pure nothrow 568 { 569 return (findData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0; 570 } 571 572 /// Returns true if this is a directory. 573 /// You probably want to use this one to decide whether to recurse. 574 @property bool entryIsDir() const pure nothrow 575 { 576 return isDir && !isSymlink; 577 } 578 579 /// Returns the raw Windows attributes of this directory entry. 580 @property uint attributes() const pure nothrow 581 { 582 return findData.dwFileAttributes; 583 } 584 585 /// Returns the size in bytes of this directory entry. 586 @property ulong size() const pure nothrow 587 { 588 return makeUlong(findData.nFileSizeLow, findData.nFileSizeHigh); 589 } 590 591 /// Returns the creation time of this directory entry. 592 @property SysTime timeCreated() const 593 { 594 return FILETIMEToSysTime(&findData.ftCreationTime); 595 } 596 597 /// Returns the last access time of this directory entry. 598 @property SysTime timeLastAccessed() const 599 { 600 return FILETIMEToSysTime(&findData.ftLastAccessTime); 601 } 602 603 /// Returns the last modification time of this directory entry. 604 @property SysTime timeLastModified() const 605 { 606 return FILETIMEToSysTime(&findData.ftLastWriteTime); 607 } 608 609 /// Returns the 64-bit unique file index of this file. 610 @property ulong fileID() 611 { 612 return getFileID(fullName); 613 } 614 } 615 } 616 617 version (Posix) 618 { 619 // The length of the buffer on the stack. 620 enum initialPathBufLength = 256; 621 622 private static void scan(DIR* dir, int dirFD, Entry* parentEntry) 623 { 624 Entry entry = void; 625 entry.parent = parentEntry; 626 entry.context = entry.parent.context; 627 entry.dirFD = dirFD; 628 629 scope(exit) closedir(dir); 630 631 dirent* ent; 632 while ((ent = readdir(dir)) != null) 633 { 634 // Apparently happens on some OS X versions. 635 enforce(ent.d_name[0], 636 "Empty dir entry name (OS bug?)"); 637 638 // Skip "." and ".." 639 if (ent.d_name[0] == '.' && ( 640 ent.d_name[1] == 0 || 641 (ent.d_name[1] == '.' && ent.d_name[2] == 0))) 642 continue; 643 644 entry.ent = ent; 645 entry.name = ent.d_name.ptr; 646 entry.data = Entry.Data.init; 647 entry.context.callHandler(&entry); 648 if (entry.context.timeToStop) 649 break; 650 } 651 } 652 } 653 654 enum isPath(Path) = (isForwardRange!Path || isSomeString!Path) && 655 isSomeChar!(ElementEncodingType!Path); 656 657 import core.stdc.stdlib : malloc, realloc, free; 658 659 static FSChar[] reallocPathBuf(FSChar[] buf, size_t newLength) nothrow @nogc 660 { 661 if (buf.length == initialPathBufLength) // current buffer is on stack 662 { 663 auto ptr = cast(FSChar*) malloc(newLength * FSChar.sizeof); 664 ptr[0 .. buf.length] = buf[]; 665 return ptr[0 .. newLength]; 666 } 667 else // current buffer on C heap (malloc'd above) 668 { 669 auto ptr = cast(FSChar*) realloc(buf.ptr, newLength * FSChar.sizeof); 670 return ptr[0 .. newLength]; 671 } 672 } 673 674 // Append a string to the buffer, reallocating as necessary. 675 // Returns the new length of the string in the buffer. 676 static size_t appendString(Str)(ref FSChar[] buf, size_t pos, Str str) nothrow @nogc 677 if (isPath!Str) 678 { 679 static if (ElementEncodingType!Str.sizeof == FSChar.sizeof 680 && is(typeof(str.length))) 681 { 682 // No transcoding needed and length known 683 auto remainingSpace = buf.length - pos; 684 if (str.length > remainingSpace) 685 buf = reallocPathBuf(buf, (pos + str.length) * 3 / 2); 686 buf[pos .. pos + str.length] = str[]; 687 pos += str.length; 688 } 689 else 690 { 691 // Need to transcode 692 auto p = buf.ptr + pos; 693 auto bufEnd = buf.ptr + buf.length; 694 foreach (c; byUTF!FSChar(str)) 695 { 696 if (p == bufEnd) // out of room 697 { 698 auto newBuf = reallocPathBuf(buf, buf.length * 3 / 2); 699 700 // Update pointers to point into the new buffer. 701 p = newBuf.ptr + (p - buf.ptr); 702 buf = newBuf; 703 bufEnd = buf.ptr + buf.length; 704 } 705 *p++ = c; 706 } 707 pos = p - buf.ptr; 708 } 709 return pos; 710 } 711 712 version (Windows) 713 { 714 mixin(importWin32!(q{winbase})); 715 import ae.sys.windows.misc : makeUlong; 716 717 // The length of the buffer on the stack. 718 enum initialPathBufLength = MAX_PATH; 719 720 enum FIND_FIRST_EX_LARGE_FETCH = 2; 721 enum FindExInfoBasic = cast(FINDEX_INFO_LEVELS)1; 722 723 static void scan(Entry* parentEntry) 724 { 725 Entry entry = void; 726 entry.parent = parentEntry; 727 entry.context = parentEntry.context; 728 729 HANDLE hFind = FindFirstFileExW( 730 entry.context.pathBuf.ptr, 731 FindExInfoBasic, 732 &entry.findData, 733 FINDEX_SEARCH_OPS.FindExSearchNameMatch, 734 null, 735 FIND_FIRST_EX_LARGE_FETCH, // https://blogs.msdn.microsoft.com/oldnewthing/20131024-00/?p=2843 736 ); 737 if (hFind == INVALID_HANDLE_VALUE) 738 throw new WindowsException(GetLastError(), 739 text("FindFirstFileW: ", parentEntry.fullNameFS)); 740 scope(exit) FindClose(hFind); 741 do 742 { 743 // Skip "." and ".." 744 auto fn = entry.findData.cFileName.ptr; 745 if (fn[0] == '.' && ( 746 fn[1] == 0 || 747 (fn[1] == '.' && fn[2] == 0))) 748 continue; 749 750 entry.data = Entry.Data.init; 751 entry.context.callHandler(&entry); 752 if (entry.context.timeToStop) 753 break; 754 } 755 while (FindNextFileW(hFind, &entry.findData)); 756 if (GetLastError() != ERROR_NO_MORE_FILES) 757 throw new WindowsException(GetLastError(), 758 text("FindNextFileW: ", parentEntry.fullNameFS)); 759 } 760 } 761 762 public void listDir(Path)(Path dirPath) 763 if (isPath!Path) 764 { 765 import std.internal.cstring; 766 767 if (dirPath.empty) 768 return listDir("."); 769 770 Context context; 771 772 FSChar[initialPathBufLength] pathBufStore = void; 773 context.pathBuf = pathBufStore[]; 774 775 scope (exit) 776 { 777 if (context.pathBuf.length != initialPathBufLength) 778 free(context.pathBuf.ptr); 779 } 780 781 Entry rootEntry; 782 rootEntry.context = &context; 783 784 auto endPos = appendString(context.pathBuf, 0, dirPath); 785 rootEntry.data.pathTailPos = endPos - (endPos > 0 && context.pathBuf[endPos - 1].isDirSeparator() ? 1 : 0); 786 assert(rootEntry.data.pathTailPos > 0); 787 788 static if (includeRoot) 789 { 790 version (Posix) 791 { 792 version (OSX) 793 enum AT_FDCWD = -2; 794 else 795 import core.sys.posix.fcntl : AT_FDCWD; 796 797 rootEntry.dirFD = AT_FDCWD; 798 rootEntry.ent = null; 799 auto name = tempCString(dirPath); 800 rootEntry.name = name; 801 802 context.callHandler(&rootEntry); 803 } 804 else 805 version (Windows) 806 { 807 while (rootEntry.data.pathTailPos && !context.pathBuf[rootEntry.data.pathTailPos].isDirSeparator()) 808 rootEntry.data.pathTailPos--; 809 scan(&rootEntry); 810 } 811 } 812 else 813 { 814 version (Posix) 815 { 816 auto dir = opendir(tempCString(dirPath)); 817 checkDir(dir, dirPath); 818 819 scan(dir, dirfd(dir), &rootEntry); 820 } 821 else 822 version (Windows) 823 { 824 const WCHAR[] tailString = endPos == 0 || context.pathBuf[endPos - 1].isDirSeparator() ? "*.*\0"w : "\\*.*\0"w; 825 appendString(context.pathBuf, endPos, tailString); 826 827 scan(&rootEntry); 828 } 829 } 830 } 831 832 // Workaround for https://github.com/ldc-developers/ldc/issues/2960 833 version (Posix) 834 private void checkDir(Path)(DIR* dir, auto ref Path dirPath) 835 { 836 errnoEnforce(dir, "Failed to open directory " ~ dirPath); 837 } 838 } 839 840 unittest 841 { 842 auto tmpDir = deleteme ~ "-dir"; 843 if (tmpDir.exists) tmpDir.removeRecurse(); 844 mkdirRecurse(tmpDir); 845 scope(exit) rmdirRecurse(tmpDir); 846 847 touch(tmpDir ~ "/a"); 848 touch(tmpDir ~ "/b"); 849 mkdir(tmpDir ~ "/c"); 850 touch(tmpDir ~ "/c/1"); 851 touch(tmpDir ~ "/c/2"); 852 853 string[] entries; 854 listDir!((e) { 855 assert(equal(e.fullNameFS, e.fullName)); 856 entries ~= e.fullName.relPath(tmpDir); 857 if (e.entryIsDir) 858 e.recurse(); 859 })(tmpDir); 860 861 assert(equal( 862 entries.sort, 863 ["a", "b", "c", "c/1", "c/2"].map!(name => name.replace("/", dirSeparator)), 864 ), text(entries)); 865 866 entries = null; 867 import std.ascii : isDigit; 868 listDir!((e) { 869 entries ~= e.fullName.relPath(tmpDir); 870 if (e.baseNameFS[0].isDigit) 871 e.stop(); 872 else 873 if (e.entryIsDir) 874 e.recurse(); 875 })(tmpDir); 876 877 assert(entries.length < 5 && entries[$-1][$-1].isDigit, text(entries)); 878 879 // Test Yes.includeRoot 880 tmpDir.listDir!((e) { 881 assert(e.fullName == tmpDir, e.fullName ~ " != " ~ tmpDir); 882 assert(e.entryIsDir); 883 }, Yes.includeRoot); 884 885 entries = null; 886 tmpDir.listDir!((e) { 887 assert(equal(e.fullNameFS, e.fullName)); 888 entries ~= e.fullName.relPath(tmpDir); 889 if (e.entryIsDir) 890 e.recurse(); 891 }, Yes.includeRoot); 892 893 assert(equal( 894 entries.sort, 895 [".", "a", "b", "c", "c/1", "c/2"].map!(name => name.replace("/", dirSeparator)), 896 ), text(entries)); 897 898 // Symlink test 899 (){ 900 // Wine's implementation of symlinks/junctions is incomplete 901 version (Windows) 902 if (getWineVersion()) 903 return; 904 905 dirLink("c", tmpDir ~ "/d"); 906 dirLink("x", tmpDir ~ "/e"); 907 908 string[] entries; 909 listDir!((e) { 910 entries ~= e.fullName.relPath(tmpDir); 911 if (e.entryIsDir) 912 e.recurse(); 913 })(tmpDir); 914 915 assert(equal( 916 entries.sort, 917 ["a", "b", "c", "c/1", "c/2", "d", "e"].map!(name => name.replace("/", dirSeparator)), 918 )); 919 920 // Recurse into symlinks 921 922 entries = null; 923 listDir!((e) { 924 entries ~= e.fullName.relPath(tmpDir); 925 if (e.isDir) 926 try 927 e.recurse(); 928 catch (Exception e) // broken junctions on Windows throw 929 {} 930 })(tmpDir); 931 932 assert(equal( 933 entries.sort, 934 ["a", "b", "c", "c/1", "c/2", "d", "d/1", "d/2", "e"].map!(name => name.replace("/", dirSeparator)), 935 )); 936 }(); 937 } 938 939 // ************************************************************************ 940 941 private string buildPath2(string[] segments...) { return segments.length ? buildPath(segments) : null; } 942 943 /// Shell-like expansion of ?, * and ** in path components 944 DirEntry[] fileList(string pattern) 945 { 946 auto components = cast(string[])array(pathSplitter(pattern)); 947 foreach (i, component; components[0..$-1]) 948 if (component.contains("?") || component.contains("*")) // TODO: escape? 949 { 950 DirEntry[] expansions; // TODO: filter range instead? 951 auto dir = buildPath2(components[0..i]); 952 if (component == "**") 953 expansions = array(dirEntries(dir, SpanMode.depth)); 954 else 955 expansions = array(dirEntries(dir, component, SpanMode.shallow)); 956 957 DirEntry[] result; 958 foreach (expansion; expansions) 959 if (expansion.isDir()) 960 result ~= fileList(buildPath(expansion.name ~ components[i+1..$])); 961 return result; 962 } 963 964 auto dir = buildPath2(components[0..$-1]); 965 if (!dir || exists(dir)) 966 return array(dirEntries(dir, components[$-1], SpanMode.shallow)); 967 else 968 return null; 969 } 970 971 /// ditto 972 DirEntry[] fileList(string pattern0, string[] patterns...) 973 { 974 DirEntry[] result; 975 foreach (pattern; [pattern0] ~ patterns) 976 result ~= fileList(pattern); 977 return result; 978 } 979 980 /// ditto 981 deprecated string[] fastFileList(string pattern) 982 { 983 auto components = cast(string[])array(pathSplitter(pattern)); 984 foreach (i, component; components[0..$-1]) 985 if (component.contains("?") || component.contains("*")) // TODO: escape? 986 { 987 string[] expansions; // TODO: filter range instead? 988 auto dir = buildPath2(components[0..i]); 989 if (component == "**") 990 expansions = fastListDir!true(dir); 991 else 992 expansions = fastListDir(dir, component); 993 994 string[] result; 995 foreach (expansion; expansions) 996 if (expansion.isDir()) 997 result ~= fastFileList(buildPath(expansion ~ components[i+1..$])); 998 return result; 999 } 1000 1001 auto dir = buildPath2(components[0..$-1]); 1002 if (!dir || exists(dir)) 1003 return fastListDir(dir, components[$-1]); 1004 else 1005 return null; 1006 } 1007 1008 /// ditto 1009 deprecated string[] fastFileList(string pattern0, string[] patterns...) 1010 { 1011 string[] result; 1012 foreach (pattern; [pattern0] ~ patterns) 1013 result ~= fastFileList(pattern); 1014 return result; 1015 } 1016 1017 // ************************************************************************ 1018 1019 import std.datetime; 1020 import std.exception; 1021 1022 deprecated SysTime getMTime(string name) 1023 { 1024 return timeLastModified(name); 1025 } 1026 1027 /// If target exists, update its modification time; 1028 /// otherwise create it as an empty file. 1029 void touch(in char[] target) 1030 { 1031 if (exists(target)) 1032 { 1033 auto now = Clock.currTime(); 1034 setTimes(target, now, now); 1035 } 1036 else 1037 std.file.write(target, ""); 1038 } 1039 1040 /// Returns true if the target file doesn't exist, 1041 /// or source is newer than the target. 1042 bool newerThan(string source, string target) 1043 { 1044 if (!target.exists) 1045 return true; 1046 return source.timeLastModified() > target.timeLastModified(); 1047 } 1048 1049 /// Returns true if the target file doesn't exist, 1050 /// or any of the sources are newer than the target. 1051 bool anyNewerThan(string[] sources, string target) 1052 { 1053 if (!target.exists) 1054 return true; 1055 auto targetTime = target.timeLastModified(); 1056 return sources.any!(source => source.timeLastModified() > targetTime)(); 1057 } 1058 1059 version (Posix) 1060 { 1061 import core.sys.posix.sys.stat; 1062 import core.sys.posix.unistd; 1063 1064 /// Get the ID of the user owning this file. 1065 int getOwner(string fn) 1066 { 1067 stat_t s; 1068 errnoEnforce(stat(toStringz(fn), &s) == 0, "stat: " ~ fn); 1069 return s.st_uid; 1070 } 1071 1072 /// Get the ID of the group owning this file. 1073 int getGroup(string fn) 1074 { 1075 stat_t s; 1076 errnoEnforce(stat(toStringz(fn), &s) == 0, "stat: " ~ fn); 1077 return s.st_gid; 1078 } 1079 1080 /// Set the owner user and group of this file. 1081 void setOwner(string fn, int uid, int gid) 1082 { 1083 errnoEnforce(chown(toStringz(fn), uid, gid) == 0, "chown: " ~ fn); 1084 } 1085 } 1086 1087 /// Try to rename; copy/delete if rename fails 1088 void move(string src, string dst) 1089 { 1090 try 1091 src.rename(dst); 1092 catch (Exception e) 1093 { 1094 atomicCopy(src, dst); 1095 src.remove(); 1096 } 1097 } 1098 1099 /// Make sure that the given directory exists 1100 /// (and create parent directories as necessary). 1101 void ensureDirExists(string path) 1102 { 1103 if (!path.exists) 1104 path.mkdirRecurse(); 1105 } 1106 1107 /// Make sure that the path to the given file name 1108 /// exists (and create directories as necessary). 1109 void ensurePathExists(string fn) 1110 { 1111 fn.dirName.ensureDirExists(); 1112 } 1113 1114 static import core.stdc.errno; 1115 version (Windows) 1116 { 1117 static import core.sys.windows.winerror; 1118 static import std.windows.syserror; 1119 static import ae.sys.windows.exception; 1120 } 1121 1122 /// Catch common Phobos exception types corresponding to file operations. 1123 bool collectOSError(alias checkCError, alias checkWinError)(scope void delegate() operation) 1124 { 1125 mixin(() { 1126 string code = q{ 1127 try 1128 { 1129 operation(); 1130 return true; 1131 } 1132 catch (FileException e) 1133 { 1134 version (Windows) 1135 bool collect = checkWinError(e.errno); 1136 else 1137 bool collect = checkCError(e.errno); 1138 if (collect) 1139 return false; 1140 else 1141 throw e; 1142 } 1143 catch (ErrnoException e) 1144 { 1145 if (checkCError(e.errno)) 1146 return false; 1147 else 1148 throw e; 1149 } 1150 }; 1151 version(Windows) code ~= q{ 1152 catch (std.windows.syserror.WindowsException e) 1153 { 1154 if (checkWinError(e.code)) 1155 return false; 1156 else 1157 throw e; 1158 } 1159 catch (ae.sys.windows.exception.WindowsException e) 1160 { 1161 if (checkWinError(e.code)) 1162 return false; 1163 else 1164 throw e; 1165 } 1166 }; 1167 return code; 1168 }()); 1169 } 1170 1171 /// Collect a "file not found" error. 1172 alias collectNotFoundError = collectOSError!( 1173 errno => errno == core.stdc.errno.ENOENT, 1174 (code) { version(Windows) return 1175 code == core.sys.windows.winerror.ERROR_FILE_NOT_FOUND || 1176 code == core.sys.windows.winerror.ERROR_PATH_NOT_FOUND; }, 1177 ); 1178 1179 /// 1180 unittest 1181 { 1182 auto fn = deleteme; 1183 if (fn.exists) fn.removeRecurse(); 1184 foreach (dg; [ 1185 { openFile(fn, "rb"); }, 1186 { mkdir(fn.buildPath("b")); }, 1187 { hardLink(fn, fn ~ "2"); }, 1188 ]) 1189 assert(!dg.collectNotFoundError); 1190 } 1191 1192 /// Collect a "file already exists" error. 1193 alias collectFileExistsError = collectOSError!( 1194 errno => errno == core.stdc.errno.EEXIST, 1195 (code) { version(Windows) return 1196 code == core.sys.windows.winerror.ERROR_FILE_EXISTS || 1197 code == core.sys.windows.winerror.ERROR_ALREADY_EXISTS; }, 1198 ); 1199 1200 /// 1201 unittest 1202 { 1203 auto fn = deleteme; 1204 foreach (dg; [ 1205 { mkdir(fn); }, 1206 { openFile(fn, "wxb"); }, 1207 { touch(fn ~ "2"); hardLink(fn ~ "2", fn); }, 1208 ]) 1209 { 1210 if (fn.exists) fn.removeRecurse(); 1211 assert( dg.collectFileExistsError); 1212 assert(!dg.collectFileExistsError); 1213 } 1214 } 1215 1216 import ae.utils.text; 1217 1218 /// Forcibly remove a file or directory. 1219 /// If atomic is true, the entire directory is deleted "atomically" 1220 /// (it is first moved/renamed to another location). 1221 /// On Windows, this will move the file/directory out of the way, 1222 /// if it is in use and cannot be deleted (but can be renamed). 1223 void forceDelete(Flag!"atomic" atomic=Yes.atomic)(string fn, Flag!"recursive" recursive = No.recursive) 1224 { 1225 import std.process : environment; 1226 version(Windows) 1227 { 1228 mixin(importWin32!q{winnt}); 1229 mixin(importWin32!q{winbase}); 1230 } 1231 1232 auto name = fn.baseName(); 1233 fn = fn.absolutePath().longPath(); 1234 1235 version(Windows) 1236 { 1237 auto fnW = toUTF16z(fn); 1238 auto attr = GetFileAttributesW(fnW); 1239 wenforce(attr != INVALID_FILE_ATTRIBUTES, "GetFileAttributes"); 1240 if (attr & FILE_ATTRIBUTE_READONLY) 1241 SetFileAttributesW(fnW, attr & ~FILE_ATTRIBUTE_READONLY).wenforce("SetFileAttributes"); 1242 } 1243 1244 static if (atomic) 1245 { 1246 // To avoid zombifying locked directories, try renaming it first. 1247 // Attempting to delete a locked directory will make it inaccessible. 1248 1249 bool tryMoveTo(string target) 1250 { 1251 target = target.longPath(); 1252 if (target.endsWith(dirSeparator)) 1253 target = target[0..$-1]; 1254 if (target.length && !target.exists) 1255 return false; 1256 1257 string newfn; 1258 do 1259 newfn = format("%s%sdeleted-%s.%s.%s", target, dirSeparator, name, thisProcessID, randomString()); 1260 while (newfn.exists); 1261 1262 version(Windows) 1263 { 1264 auto newfnW = toUTF16z(newfn); 1265 if (!MoveFileW(fnW, newfnW)) 1266 return false; 1267 } 1268 else 1269 { 1270 try 1271 rename(fn, newfn); 1272 catch (FileException e) 1273 return false; 1274 } 1275 1276 fn = newfn; 1277 version(Windows) fnW = newfnW; 1278 return true; 1279 } 1280 1281 void tryMove() 1282 { 1283 auto tmp = environment.get("TEMP"); 1284 if (tmp) 1285 if (tryMoveTo(tmp)) 1286 return; 1287 1288 version(Windows) 1289 string tempDir = fn[0..7]~"Temp"; 1290 else 1291 enum tempDir = "/tmp"; 1292 1293 if (tryMoveTo(tempDir)) 1294 return; 1295 1296 if (tryMoveTo(fn.dirName())) 1297 return; 1298 1299 throw new Exception("Unable to delete " ~ fn ~ " atomically (all rename attempts failed)"); 1300 } 1301 1302 tryMove(); 1303 } 1304 1305 version(Windows) 1306 { 1307 if (attr & FILE_ATTRIBUTE_DIRECTORY) 1308 { 1309 if (recursive && (attr & FILE_ATTRIBUTE_REPARSE_POINT) == 0) 1310 { 1311 foreach (de; fn.dirEntries(SpanMode.shallow)) 1312 forceDelete!(No.atomic)(de.name, Yes.recursive); 1313 } 1314 // Will fail if !recursive and directory is not empty 1315 RemoveDirectoryW(fnW).wenforce("RemoveDirectory"); 1316 } 1317 else 1318 DeleteFileW(fnW).wenforce("DeleteFile"); 1319 } 1320 else 1321 { 1322 if (recursive) 1323 fn.removeRecurse(); 1324 else 1325 if (fn.isDir) 1326 fn.rmdir(); 1327 else 1328 fn.remove(); 1329 } 1330 } 1331 1332 1333 deprecated void forceDelete(bool atomic)(string fn, bool recursive = false) { forceDelete!(cast(Flag!"atomic")atomic)(fn, cast(Flag!"recursive")recursive); } 1334 //deprecated void forceDelete()(string fn, bool recursive) { forceDelete!(Yes.atomic)(fn, cast(Flag!"recursive")recursive); } 1335 1336 deprecated unittest 1337 { 1338 mkdir("testdir"); touch("testdir/b"); forceDelete!(false )("testdir", true); 1339 mkdir("testdir"); touch("testdir/b"); forceDelete!(true )("testdir", true); 1340 } 1341 1342 unittest 1343 { 1344 mkdir("testdir"); touch("testdir/b"); forceDelete ("testdir", Yes.recursive); 1345 mkdir("testdir"); touch("testdir/b"); forceDelete!(No .atomic)("testdir", Yes.recursive); 1346 mkdir("testdir"); touch("testdir/b"); forceDelete!(Yes.atomic)("testdir", Yes.recursive); 1347 } 1348 1349 /// If fn is a directory, delete it recursively. 1350 /// Otherwise, delete the file or symlink fn. 1351 void removeRecurse(string fn) 1352 { 1353 auto attr = fn.getAttributes(); 1354 if (attr.attrIsSymlink) 1355 { 1356 version (Windows) 1357 if (attr.attrIsDir) 1358 fn.rmdir(); 1359 else 1360 fn.remove(); 1361 else 1362 fn.remove(); 1363 } 1364 else 1365 if (attr.attrIsDir) 1366 version (Windows) 1367 fn.forceDelete!(No.atomic)(Yes.recursive); // For read-only files 1368 else 1369 fn.rmdirRecurse(); 1370 else 1371 fn.remove(); 1372 } 1373 1374 /// Create an empty directory, deleting 1375 /// all its contents if it already exists. 1376 void recreateEmptyDirectory()(string dir) 1377 { 1378 if (dir.exists) 1379 dir.forceDelete(Yes.recursive); 1380 mkdir(dir); 1381 } 1382 1383 /// Copy a directory recursively. 1384 void copyRecurse(DirEntry src, string dst) 1385 { 1386 version (Posix) 1387 if (src.isSymlink) 1388 return symlink(dst, readLink(src)); 1389 if (src.isFile) 1390 return copy(src, dst, PreserveAttributes.yes); 1391 dst.mkdir(); 1392 foreach (de; src.dirEntries(SpanMode.shallow)) 1393 copyRecurse(de, dst.buildPath(de.baseName)); 1394 } 1395 void copyRecurse(string src, string dst) { copyRecurse(DirEntry(src), dst); } /// ditto 1396 1397 /// Return true if the given file would be hidden from directory listings. 1398 /// Returns true for files starting with `'.'`, and, on Windows, hidden files. 1399 bool isHidden()(string fn) 1400 { 1401 if (baseName(fn).startsWith(".")) 1402 return true; 1403 version (Windows) 1404 { 1405 mixin(importWin32!q{winnt}); 1406 if (getAttributes(fn) & FILE_ATTRIBUTE_HIDDEN) 1407 return true; 1408 } 1409 return false; 1410 } 1411 1412 /// Return a file's unique ID. 1413 ulong getFileID()(string fn) 1414 { 1415 version (Windows) 1416 { 1417 mixin(importWin32!q{winnt}); 1418 mixin(importWin32!q{winbase}); 1419 1420 auto fnW = toUTF16z(fn); 1421 auto h = CreateFileW(fnW, FILE_READ_ATTRIBUTES, 0, null, OPEN_EXISTING, 0, HANDLE.init); 1422 wenforce(h!=INVALID_HANDLE_VALUE, fn); 1423 scope(exit) CloseHandle(h); 1424 BY_HANDLE_FILE_INFORMATION fi; 1425 GetFileInformationByHandle(h, &fi).wenforce("GetFileInformationByHandle"); 1426 1427 ULARGE_INTEGER li; 1428 li.LowPart = fi.nFileIndexLow; 1429 li.HighPart = fi.nFileIndexHigh; 1430 auto result = li.QuadPart; 1431 enforce(result, "Null file ID"); 1432 return result; 1433 } 1434 else 1435 { 1436 return DirEntry(fn).statBuf.st_ino; 1437 } 1438 } 1439 1440 unittest 1441 { 1442 auto base = deleteme; 1443 touch(base ~ "a"); 1444 scope(exit) remove(base ~ "a"); 1445 hardLink(base ~ "a", base ~ "b"); 1446 scope(exit) remove(base ~ "b"); 1447 touch(base ~ "c"); 1448 scope(exit) remove(base ~ "c"); 1449 assert(getFileID(base ~ "a") == getFileID(base ~ "b")); 1450 assert(getFileID(base ~ "a") != getFileID(base ~ "c")); 1451 } 1452 1453 deprecated alias std.file.getSize getSize2; 1454 1455 /// Using UNC paths bypasses path length limitation when using Windows wide APIs. 1456 string longPath(string s) 1457 { 1458 version (Windows) 1459 { 1460 if (!s.startsWith(`\\`)) 1461 return `\\?\` ~ s.absolutePath().buildNormalizedPath().replace(`/`, `\`); 1462 } 1463 return s; 1464 } 1465 1466 version (Windows) 1467 { 1468 static if (__traits(compiles, { mixin importWin32!q{winnt}; })) 1469 static mixin(importWin32!q{winnt}); 1470 1471 /// Common code for creating Windows reparse points. 1472 private void createReparsePoint(string reparseBufferName, string extraInitialization, string reparseTagName)(in char[] target, in char[] print, in char[] link) 1473 { 1474 mixin(importWin32!q{winbase}); 1475 mixin(importWin32!q{windef}); 1476 mixin(importWin32!q{winioctl}); 1477 1478 enum SYMLINK_FLAG_RELATIVE = 1; 1479 1480 HANDLE hLink = CreateFileW(link.toUTF16z(), GENERIC_READ | GENERIC_WRITE, 0, null, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, null); 1481 wenforce(hLink && hLink != INVALID_HANDLE_VALUE, "CreateFileW"); 1482 scope(exit) CloseHandle(hLink); 1483 1484 enum pathOffset = 1485 mixin(q{REPARSE_DATA_BUFFER..} ~ reparseBufferName) .offsetof + 1486 mixin(q{REPARSE_DATA_BUFFER..} ~ reparseBufferName)._PathBuffer.offsetof; 1487 1488 auto targetW = target.toUTF16(); 1489 auto printW = print .toUTF16(); 1490 1491 // Despite MSDN, two NUL-terminating characters are needed, one for each string. 1492 1493 auto pathBufferSize = targetW.length + 1 + printW.length + 1; // in chars 1494 auto buf = new ubyte[pathOffset + pathBufferSize * WCHAR.sizeof]; 1495 auto r = cast(REPARSE_DATA_BUFFER*)buf.ptr; 1496 1497 r.ReparseTag = mixin(reparseTagName); 1498 r.ReparseDataLength = to!WORD(buf.length - mixin(q{r..} ~ reparseBufferName).offsetof); 1499 1500 auto pathBuffer = mixin(q{r..} ~ reparseBufferName).PathBuffer; 1501 auto p = pathBuffer; 1502 1503 mixin(q{r..} ~ reparseBufferName).SubstituteNameOffset = to!WORD((p-pathBuffer) * WCHAR.sizeof); 1504 mixin(q{r..} ~ reparseBufferName).SubstituteNameLength = to!WORD(targetW.length * WCHAR.sizeof); 1505 p[0..targetW.length] = targetW; 1506 p += targetW.length; 1507 *p++ = 0; 1508 1509 mixin(q{r..} ~ reparseBufferName).PrintNameOffset = to!WORD((p-pathBuffer) * WCHAR.sizeof); 1510 mixin(q{r..} ~ reparseBufferName).PrintNameLength = to!WORD(printW .length * WCHAR.sizeof); 1511 p[0..printW.length] = printW; 1512 p += printW.length; 1513 *p++ = 0; 1514 1515 assert(p-pathBuffer == pathBufferSize); 1516 1517 mixin(extraInitialization); 1518 1519 DWORD dwRet; // Needed despite MSDN 1520 DeviceIoControl(hLink, FSCTL_SET_REPARSE_POINT, buf.ptr, buf.length.to!DWORD(), null, 0, &dwRet, null).wenforce("DeviceIoControl"); 1521 } 1522 1523 /// Attempt to acquire the specified privilege. 1524 void acquirePrivilege(S)(S name) 1525 { 1526 mixin(importWin32!q{winbase}); 1527 mixin(importWin32!q{windef}); 1528 1529 import ae.sys.windows; 1530 1531 HANDLE hToken = null; 1532 wenforce(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)); 1533 scope(exit) CloseHandle(hToken); 1534 1535 TOKEN_PRIVILEGES tp; 1536 wenforce(LookupPrivilegeValue(null, name.toUTF16z(), &tp.Privileges[0].Luid), "LookupPrivilegeValue"); 1537 1538 tp.PrivilegeCount = 1; 1539 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 1540 wenforce(AdjustTokenPrivileges(hToken, FALSE, &tp, cast(DWORD)TOKEN_PRIVILEGES.sizeof, null, null), "AdjustTokenPrivileges"); 1541 } 1542 1543 /// Link a directory. 1544 /// Uses symlinks on POSIX, and directory junctions on Windows. 1545 void dirLink()(in char[] original, in char[] link) 1546 { 1547 mkdir(link); 1548 scope(failure) rmdir(link); 1549 1550 auto target = `\??\` ~ (cast(string)original).absolutePath((cast(string)link.dirName).absolutePath).buildNormalizedPath; 1551 if (target[$-1] != '\\') 1552 target ~= '\\'; 1553 1554 createReparsePoint!(q{MountPointReparseBuffer}, q{}, q{IO_REPARSE_TAG_MOUNT_POINT})(target, null, link); 1555 } 1556 1557 /// Windows implementation of `std.file.symlink`. 1558 void symlink()(in char[] original, in char[] link) 1559 { 1560 mixin(importWin32!q{winnt}); 1561 1562 acquirePrivilege(SE_CREATE_SYMBOLIC_LINK_NAME); 1563 1564 touch(link); 1565 scope(failure) remove(link); 1566 1567 createReparsePoint!(q{SymbolicLinkReparseBuffer}, q{r.SymbolicLinkReparseBuffer.Flags = link.isAbsolute() ? 0 : SYMLINK_FLAG_RELATIVE;}, q{IO_REPARSE_TAG_SYMLINK})(original, original, link); 1568 } 1569 } 1570 else 1571 alias std.file.symlink dirLink; /// `std.file.symlink` is used to implement `dirLink` on POSIX. 1572 1573 version(Windows) version(unittest) static mixin(importWin32!q{winnt}); 1574 1575 unittest 1576 { 1577 // Wine's implementation of symlinks/junctions is incomplete 1578 version (Windows) 1579 if (getWineVersion()) 1580 return; 1581 1582 mkdir("a"); scope(exit) rmdir("a"[]); 1583 touch("a/f"); scope(exit) remove("a/f"); 1584 dirLink("a", "b"); scope(exit) version(Windows) rmdir("b"); else remove("b"); 1585 //symlink("a/f", "c"); scope(exit) remove("c"); 1586 assert("b".isSymlink()); 1587 //assert("c".isSymlink()); 1588 assert("b/f".exists()); 1589 } 1590 1591 version (Windows) 1592 { 1593 /// Create a hard link. 1594 void hardLink()(string src, string dst) 1595 { 1596 mixin(importWin32!q{w32api}); 1597 1598 static assert(_WIN32_WINNT >= 0x501, "CreateHardLinkW not available for target Windows platform. Specify -version=WindowsXP"); 1599 1600 mixin(importWin32!q{winnt}); 1601 mixin(importWin32!q{winbase}); 1602 1603 wenforce(CreateHardLinkW(toUTF16z(dst), toUTF16z(src), null), "CreateHardLink failed: " ~ src ~ " -> " ~ dst); 1604 } 1605 1606 /// Deletes a file, which might be a read-only hard link 1607 /// (thus, deletes the read-only file/link without affecting other links to it). 1608 void deleteHardLink()(string fn) 1609 { 1610 mixin(importWin32!q{winbase}); 1611 1612 auto fnW = toUTF16z(fn); 1613 1614 DWORD attrs = GetFileAttributesW(fnW); 1615 wenforce(attrs != INVALID_FILE_ATTRIBUTES, "GetFileAttributesW failed: " ~ fn); 1616 1617 if (attrs & FILE_ATTRIBUTE_READONLY) 1618 SetFileAttributesW(fnW, attrs & ~FILE_ATTRIBUTE_READONLY) 1619 .wenforce("SetFileAttributesW failed: " ~ fn); 1620 HANDLE h = CreateFileW(fnW, GENERIC_READ|GENERIC_WRITE, 7, null, OPEN_EXISTING, 1621 FILE_FLAG_DELETE_ON_CLOSE, null); 1622 wenforce(h != INVALID_HANDLE_VALUE, "CreateFileW failed: " ~ fn); 1623 if (attrs & FILE_ATTRIBUTE_READONLY) 1624 SetFileAttributesW(fnW, attrs) 1625 .wenforce("SetFileAttributesW failed: " ~ fn); 1626 CloseHandle(h).wenforce("CloseHandle failed: " ~ fn); 1627 } 1628 } 1629 version (Posix) 1630 { 1631 /// Create a hard link. 1632 void hardLink()(string src, string dst) 1633 { 1634 import core.sys.posix.unistd; 1635 errnoEnforce(link(toUTFz!(const char*)(src), toUTFz!(const char*)(dst)) == 0, "link() failed: " ~ dst); 1636 } 1637 1638 alias deleteHardLink = remove; /// `std.file.remove` is used to implement `deleteHardLink` on POSIX. 1639 } 1640 1641 unittest 1642 { 1643 write("a", "foo"); scope(exit) remove("a"); 1644 hardLink("a", "b"); 1645 assert("b".readText == "foo"); 1646 deleteHardLink("b"); 1647 assert(!"b".exists); 1648 } 1649 1650 version (Posix) 1651 { 1652 /// Wrapper around the C `realpath` function. 1653 string realPath(string path) 1654 { 1655 // TODO: Windows version 1656 import core.sys.posix.stdlib; 1657 auto p = realpath(toUTFz!(const char*)(path), null); 1658 errnoEnforce(p, "realpath"); 1659 string result = fromStringz(p).idup; 1660 free(p); 1661 return result; 1662 } 1663 } 1664 1665 // /proc/self/mounts parsing 1666 version (linux) 1667 { 1668 /// A parsed line from /proc/self/mounts. 1669 struct MountInfo 1670 { 1671 string spec; /// device path 1672 string file; /// mount path 1673 string vfstype; /// file system 1674 string mntops; /// options 1675 int freq; /// dump flag 1676 int passno; /// fsck order 1677 } 1678 1679 private string unescapeMountString(in char[] s) 1680 { 1681 string result; 1682 1683 size_t p = 0; 1684 for (size_t i=0; i+3<s.length;) 1685 { 1686 auto c = s[i]; 1687 if (c == '\\') 1688 { 1689 result ~= s[p..i]; 1690 result ~= to!int(s[i+1..i+4], 8); 1691 i += 4; 1692 p = i; 1693 } 1694 else 1695 i++; 1696 } 1697 result ~= s[p..$]; 1698 return result; 1699 } 1700 1701 unittest 1702 { 1703 assert(unescapeMountString(`a\040b\040c`) == "a b c"); 1704 assert(unescapeMountString(`\040`) == " "); 1705 } 1706 1707 /// Parse a line from /proc/self/mounts. 1708 MountInfo parseMountInfo(in char[] line) 1709 { 1710 const(char)[][6] parts; 1711 copy(line.splitter(" "), parts[]); 1712 return MountInfo( 1713 unescapeMountString(parts[0]), 1714 unescapeMountString(parts[1]), 1715 unescapeMountString(parts[2]), 1716 unescapeMountString(parts[3]), 1717 parts[4].to!int, 1718 parts[5].to!int, 1719 ); 1720 } 1721 1722 /// Returns an iterator of MountInfo structs. 1723 auto getMounts() 1724 { 1725 return File("/proc/self/mounts", "rb").byLine().map!parseMountInfo(); 1726 } 1727 1728 /// Get MountInfo with longest mount point matching path. 1729 /// Returns MountInfo.init if none match. 1730 MountInfo getPathMountInfo(string path) 1731 { 1732 path = realPath(path); 1733 size_t bestLength; MountInfo bestInfo; 1734 foreach (ref info; getMounts()) 1735 { 1736 if (path.pathStartsWith(info.file)) 1737 { 1738 if (bestLength < info.file.length) 1739 { 1740 bestLength = info.file.length; 1741 bestInfo = info; 1742 } 1743 } 1744 } 1745 return bestInfo; 1746 } 1747 1748 /// Get the name of the filesystem that the given path is mounted under. 1749 /// Returns null if none match. 1750 string getPathFilesystem(string path) 1751 { 1752 return getPathMountInfo(path).vfstype; 1753 } 1754 } 1755 1756 // **************************************************************************** 1757 1758 version (linux) 1759 { 1760 import core.sys.linux.sys.xattr; 1761 import core.stdc.errno; 1762 private alias ENOATTR = ENODATA; 1763 1764 /// AA-like object for accessing a file's extended attributes. 1765 struct XAttrs(Obj, string funPrefix) 1766 { 1767 private Obj obj; 1768 1769 mixin("alias getFun = " ~ funPrefix ~ "getxattr;"); 1770 mixin("alias setFun = " ~ funPrefix ~ "setxattr;"); 1771 mixin("alias removeFun = " ~ funPrefix ~ "removexattr;"); 1772 mixin("alias listFun = " ~ funPrefix ~ "listxattr;"); 1773 1774 /// True if extended attributes are supported on this filesystem. 1775 bool supported() 1776 { 1777 auto size = getFun(obj, "user.\x01", null, 0); 1778 return size >= 0 || errno != EOPNOTSUPP; 1779 } 1780 1781 /// Read an extended attribute. 1782 void[] opIndex(string key) 1783 { 1784 auto cKey = key.toStringz(); 1785 size_t size = 0; 1786 void[] buf; 1787 do 1788 { 1789 buf.length = size; 1790 size = getFun(obj, cKey, buf.ptr, buf.length); 1791 errnoEnforce(size >= 0, __traits(identifier, getFun)); 1792 } while (size != buf.length); 1793 return buf; 1794 } 1795 1796 /// Check if an extended attribute is present. 1797 bool opBinaryRight(string op)(string key) 1798 if (op == "in") 1799 { 1800 auto cKey = key.toStringz(); 1801 auto size = getFun(obj, cKey, null, 0); 1802 if (size >= 0) 1803 return true; 1804 else 1805 if (errno == ENOATTR) 1806 return false; 1807 else 1808 errnoEnforce(false, __traits(identifier, getFun)); 1809 assert(false); 1810 } 1811 1812 /// Write an extended attribute. 1813 void opIndexAssign(in void[] value, string key) 1814 { 1815 auto ret = setFun(obj, key.toStringz(), value.ptr, value.length, 0); 1816 errnoEnforce(ret == 0, __traits(identifier, setFun)); 1817 } 1818 1819 /// Delete an extended attribute. 1820 void remove(string key) 1821 { 1822 auto ret = removeFun(obj, key.toStringz()); 1823 errnoEnforce(ret == 0, __traits(identifier, removeFun)); 1824 } 1825 1826 /// Return a list of all extended attribute names. 1827 string[] keys() 1828 { 1829 size_t size = 0; 1830 char[] buf; 1831 do 1832 { 1833 buf.length = size; 1834 size = listFun(obj, buf.ptr, buf.length); 1835 errnoEnforce(size >= 0, __traits(identifier, listFun)); 1836 } while (size != buf.length); 1837 1838 char[][] result; 1839 size_t start; 1840 foreach (p, c; buf) 1841 if (!c) 1842 { 1843 result ~= buf[start..p]; 1844 start = p+1; 1845 } 1846 1847 return cast(string[])result; 1848 } 1849 } 1850 1851 /// Return `XAttrs` for the given path, 1852 /// or the link destination if the path leads to as symbolic link. 1853 auto xAttrs(string path) 1854 { 1855 return XAttrs!(const(char)*, "")(path.toStringz()); 1856 } 1857 1858 /// Return `XAttrs` for the given path. 1859 auto linkXAttrs(string path) 1860 { 1861 return XAttrs!(const(char)*, "l")(path.toStringz()); 1862 } 1863 1864 /// Return `XAttrs` for the given open file. 1865 auto xAttrs(ref const File f) 1866 { 1867 return XAttrs!(int, "f")(f.fileno); 1868 } 1869 1870 /// 1871 unittest 1872 { 1873 if (!xAttrs(".").supported) 1874 { 1875 import std.stdio : stderr; 1876 stderr.writeln("ae.sys.file: xattrs not supported on current filesystem, skipping test."); 1877 return; 1878 } 1879 1880 enum fn = "test.txt"; 1881 std.file.write(fn, "test"); 1882 scope(exit) remove(fn); 1883 1884 auto attrs = xAttrs(fn); 1885 enum key = "user.foo"; 1886 assert(key !in attrs); 1887 assert(attrs.keys == []); 1888 1889 attrs[key] = "bar"; 1890 assert(key in attrs); 1891 assert(attrs[key] == "bar"); 1892 assert(attrs.keys == [key]); 1893 1894 attrs.remove(key); 1895 assert(key !in attrs); 1896 assert(attrs.keys == []); 1897 } 1898 } 1899 1900 // **************************************************************************** 1901 1902 version (Windows) 1903 { 1904 /// Enumerate all hard links to the specified file. 1905 // TODO: Return a range 1906 string[] enumerateHardLinks()(string fn) 1907 { 1908 mixin(importWin32!q{winnt}); 1909 mixin(importWin32!q{winbase}); 1910 1911 alias extern(System) HANDLE function(LPCWSTR lpFileName, DWORD dwFlags, LPDWORD StringLength, PWCHAR LinkName) TFindFirstFileNameW; 1912 alias extern(System) BOOL function(HANDLE hFindStream, LPDWORD StringLength, PWCHAR LinkName) TFindNextFileNameW; 1913 1914 auto kernel32 = GetModuleHandle("kernel32.dll"); 1915 auto FindFirstFileNameW = cast(TFindFirstFileNameW)GetProcAddress(kernel32, "FindFirstFileNameW").wenforce("GetProcAddress(FindFirstFileNameW)"); 1916 auto FindNextFileNameW = cast(TFindNextFileNameW)GetProcAddress(kernel32, "FindNextFileNameW").wenforce("GetProcAddress(FindNextFileNameW)"); 1917 1918 static WCHAR[0x8000] buf; 1919 DWORD len = buf.length; 1920 auto h = FindFirstFileNameW(toUTF16z(fn), 0, &len, buf.ptr); 1921 wenforce(h != INVALID_HANDLE_VALUE, "FindFirstFileNameW"); 1922 scope(exit) FindClose(h); 1923 1924 string[] result; 1925 do 1926 { 1927 enforce(len > 0 && len < buf.length && buf[len-1] == 0, "Bad FindFirst/NextFileNameW result"); 1928 result ~= buf[0..len-1].toUTF8(); 1929 len = buf.length; 1930 auto ok = FindNextFileNameW(h, &len, buf.ptr); 1931 if (!ok && GetLastError() == ERROR_HANDLE_EOF) 1932 break; 1933 wenforce(ok, "FindNextFileNameW"); 1934 } while(true); 1935 return result; 1936 } 1937 } 1938 1939 /// Obtain the hard link count for the given file. 1940 uint hardLinkCount(string fn) 1941 { 1942 version (Windows) 1943 { 1944 // TODO: Optimize (don't transform strings) 1945 return cast(uint)fn.enumerateHardLinks.length; 1946 } 1947 else 1948 { 1949 import core.sys.posix.sys.stat; 1950 1951 stat_t s; 1952 errnoEnforce(stat(fn.toStringz(), &s) == 0, "stat"); 1953 return s.st_nlink.to!uint; 1954 } 1955 } 1956 1957 // https://issues.dlang.org/show_bug.cgi?id=7016 1958 version (unittest) 1959 version (Windows) 1960 import ae.sys.windows.misc : getWineVersion; 1961 1962 unittest 1963 { 1964 // FindFirstFileNameW not implemented in Wine 1965 version (Windows) 1966 if (getWineVersion()) 1967 return; 1968 1969 touch("a.test"); 1970 scope(exit) remove("a.test"); 1971 assert("a.test".hardLinkCount() == 1); 1972 1973 hardLink("a.test", "b.test"); 1974 scope(exit) remove("b.test"); 1975 assert("a.test".hardLinkCount() == 2); 1976 assert("b.test".hardLinkCount() == 2); 1977 1978 version(Windows) 1979 { 1980 auto paths = enumerateHardLinks("a.test"); 1981 assert(paths.length == 2); 1982 paths.sort(); 1983 assert(paths[0].endsWith(`\a.test`), paths[0]); 1984 assert(paths[1].endsWith(`\b.test`)); 1985 } 1986 } 1987 1988 /// Argument-reversed version of `std.file.write`, 1989 /// usable at the end of an UFCS chain. 1990 static if (is(typeof({ import std.stdio : toFile; }))) 1991 { 1992 static import std.stdio; 1993 alias toFile = std.stdio.toFile; 1994 } 1995 else 1996 { 1997 void toFile(in void[] data, in char[] name) 1998 { 1999 std.file.write(name, data); 2000 } 2001 } 2002 2003 /// Same as toFile, but accepts void[] and does not conflict with the 2004 /// std.stdio function. 2005 void writeTo(in void[] data, in char[] target) 2006 { 2007 std.file.write(target, data); 2008 } 2009 2010 /// Polyfill for Windows fopen implementations with support for UNC 2011 /// paths and the 'x' subspecifier. 2012 File openFile()(string fn, string mode = "rb") 2013 { 2014 File f; 2015 static if (is(typeof(&f.windowsHandleOpen))) 2016 { 2017 import core.sys.windows.windows; 2018 import ae.sys.windows.exception; 2019 2020 string winMode, cMode; 2021 foreach (c; mode) 2022 { 2023 switch (c) 2024 { 2025 case 'r': 2026 case 'w': 2027 case 'a': 2028 case '+': 2029 case 'x': 2030 winMode ~= c; 2031 break; 2032 case 'b': 2033 case 't': 2034 break; 2035 default: 2036 assert(false, "Unknown character in mode"); 2037 } 2038 if (c != 'x') 2039 cMode ~= c; 2040 } 2041 DWORD access, creation; 2042 bool append; 2043 switch (winMode) 2044 { 2045 case "r" : access = GENERIC_READ ; creation = OPEN_EXISTING; break; 2046 case "r+" : access = GENERIC_READ | GENERIC_WRITE; creation = OPEN_EXISTING; break; 2047 case "w" : access = GENERIC_WRITE; creation = CREATE_ALWAYS; break; 2048 case "w+" : access = GENERIC_READ | GENERIC_WRITE; creation = CREATE_ALWAYS; break; 2049 case "a" : access = GENERIC_WRITE; creation = OPEN_ALWAYS ; version (CRuntime_Microsoft) append = true; break; 2050 case "a+" : access = GENERIC_READ | GENERIC_WRITE; creation = OPEN_ALWAYS ; version (CRuntime_Microsoft) assert(false, "MSVCRT can't fdopen with a+"); else break; 2051 case "wx" : access = GENERIC_WRITE; creation = CREATE_NEW ; break; 2052 case "w+x": access = GENERIC_READ | GENERIC_WRITE; creation = CREATE_NEW ; break; 2053 case "ax" : access = GENERIC_WRITE; creation = CREATE_NEW ; version (CRuntime_Microsoft) append = true; break; 2054 case "a+x": access = GENERIC_READ | GENERIC_WRITE; creation = CREATE_NEW ; version (CRuntime_Microsoft) assert(false, "MSVCRT can't fdopen with a+"); else break; 2055 default: assert(false, "Bad file mode: " ~ mode); 2056 } 2057 2058 auto pathW = toUTF16z(longPath(fn)); 2059 auto h = CreateFileW(pathW, access, FILE_SHARE_READ, null, creation, 0, HANDLE.init); 2060 wenforce(h != INVALID_HANDLE_VALUE); 2061 2062 if (append) 2063 h.SetFilePointer(0, null, FILE_END); 2064 2065 f.windowsHandleOpen(h, cMode); 2066 } 2067 else 2068 f.open(fn, mode); 2069 return f; 2070 } 2071 2072 unittest 2073 { 2074 enum Existence { any, mustExist, mustNotExist } 2075 enum Pos { none /* not readable/writable */, start, end, empty } 2076 static struct Behavior 2077 { 2078 Existence existence; 2079 bool truncating; 2080 Pos read, write; 2081 } 2082 2083 void test(string mode, in Behavior expected) 2084 { 2085 static if (isVersion!q{CRuntime_Microsoft} || isVersion!q{OSX}) 2086 if (mode == "a+" || mode == "a+x") 2087 return; 2088 2089 Behavior behavior; 2090 2091 static int counter; 2092 auto fn = text(deleteme, counter++); 2093 2094 collectException(fn.remove()); 2095 bool mustExist = !!collectException(openFile(fn, mode)); 2096 touch(fn); 2097 bool mustNotExist = !!collectException(openFile(fn, mode)); 2098 2099 if (!mustExist) 2100 if (!mustNotExist) 2101 behavior.existence = Existence.any; 2102 else 2103 behavior.existence = Existence.mustNotExist; 2104 else 2105 if (!mustNotExist) 2106 behavior.existence = Existence.mustExist; 2107 else 2108 assert(false, "Can't open file whether it exists or not"); 2109 2110 void create() 2111 { 2112 if (mustNotExist) 2113 collectException(fn.remove()); 2114 else 2115 write(fn, "foo"); 2116 } 2117 2118 create(); 2119 openFile(fn, mode); 2120 behavior.truncating = getSize(fn) == 0; 2121 2122 create(); 2123 { 2124 auto f = openFile(fn, mode); 2125 ubyte[] buf; 2126 if (collectException(f.rawRead(new ubyte[1]), buf)) 2127 { 2128 behavior.read = Pos.none; 2129 // Work around https://issues.dlang.org/show_bug.cgi?id=19751 2130 f.reopen(fn, "w"); 2131 } 2132 else 2133 if (buf.length) 2134 behavior.read = Pos.start; 2135 else 2136 if (f.size) 2137 behavior.read = Pos.end; 2138 else 2139 behavior.read = Pos.empty; 2140 } 2141 2142 create(); 2143 { 2144 string s; 2145 { 2146 auto f = openFile(fn, mode); 2147 if (collectException(f.rawWrite("b"))) 2148 { 2149 s = null; 2150 // Work around https://issues.dlang.org/show_bug.cgi?id=19751 2151 f.reopen(fn, "w"); 2152 } 2153 else 2154 { 2155 f.close(); 2156 s = fn.readText; 2157 } 2158 } 2159 2160 if (s is null) 2161 behavior.write = Pos.none; 2162 else 2163 if (s == "b") 2164 behavior.write = Pos.empty; 2165 else 2166 if (s.endsWith("b")) 2167 behavior.write = Pos.end; 2168 else 2169 if (s.startsWith("b")) 2170 behavior.write = Pos.start; 2171 else 2172 assert(false, "Can't detect write position"); 2173 } 2174 2175 2176 if (behavior != expected) 2177 { 2178 import ae.utils.array : isOneOf; 2179 version (Windows) 2180 if (getWineVersion() && mode.isOneOf("w", "a", "wx", "ax")) 2181 { 2182 // Ignore bug in Wine msvcrt implementation 2183 return; 2184 } 2185 2186 assert(false, text(mode, ": expected ", expected, ", got ", behavior)); 2187 } 2188 } 2189 2190 test("r" , Behavior(Existence.mustExist , false, Pos.start, Pos.none )); 2191 test("r+" , Behavior(Existence.mustExist , false, Pos.start, Pos.start)); 2192 test("w" , Behavior(Existence.any , true , Pos.none , Pos.empty)); 2193 test("w+" , Behavior(Existence.any , true , Pos.empty, Pos.empty)); 2194 test("a" , Behavior(Existence.any , false, Pos.none , Pos.end )); 2195 test("a+" , Behavior(Existence.any , false, Pos.start, Pos.end )); 2196 test("wx" , Behavior(Existence.mustNotExist, true , Pos.none , Pos.empty)); 2197 test("w+x", Behavior(Existence.mustNotExist, true , Pos.empty, Pos.empty)); 2198 test("ax" , Behavior(Existence.mustNotExist, true , Pos.none , Pos.empty)); 2199 test("a+x", Behavior(Existence.mustNotExist, true , Pos.empty, Pos.empty)); 2200 } 2201 2202 private version(Windows) 2203 { 2204 version (CRuntime_Microsoft) 2205 { 2206 alias chsize_size_t = long; 2207 extern(C) int _chsize_s(int fd, chsize_size_t size); 2208 alias chsize = _chsize_s; 2209 } 2210 else 2211 { 2212 import core.stdc.config : c_long; 2213 alias chsize_size_t = c_long; 2214 extern(C) int chsize(int fd, c_long size); 2215 } 2216 } 2217 2218 /// Truncate the given file to the given size. 2219 void truncate(File f, ulong length) 2220 { 2221 f.flush(); 2222 version (Windows) 2223 chsize(f.fileno, length.to!chsize_size_t); 2224 else 2225 ftruncate(f.fileno, length.to!off_t); 2226 } 2227 2228 unittest 2229 { 2230 write("test.txt", "abcde"); 2231 auto f = File("test.txt", "r+b"); 2232 f.write("xyz"); 2233 f.truncate(f.tell); 2234 f.close(); 2235 assert("test.txt".readText == "xyz"); 2236 } 2237 2238 /// Calculate the digest of a file. 2239 auto fileDigest(Digest)(string fn) 2240 { 2241 import std.range.primitives; 2242 Digest context; 2243 context.start(); 2244 put(context, openFile(fn, "rb").byChunk(64 * 1024)); 2245 auto digest = context.finish(); 2246 return digest; 2247 } 2248 2249 /// Calculate the MD5 hash of a file. 2250 template mdFile() 2251 { 2252 import std.digest.md; 2253 alias mdFile = fileDigest!MD5; 2254 } 2255 2256 version (HAVE_WIN32) 2257 unittest 2258 { 2259 import std.digest : toHexString; 2260 write("test.txt", "Hello, world!"); 2261 scope(exit) remove("test.txt"); 2262 assert(mdFile("test.txt").toHexString() == "6CD3556DEB0DA54BCA060B4C39479839"); 2263 } 2264 2265 /// Calculate the digest of a file, and memoize it. 2266 auto fileDigestCached(Digest)(string fn) 2267 { 2268 static typeof(Digest.init.finish())[ulong] cache; 2269 auto id = getFileID(fn); 2270 auto phash = id in cache; 2271 if (phash) 2272 return *phash; 2273 return cache[id] = fileDigest!Digest(fn); 2274 } 2275 2276 /// Calculate the MD5 hash of a file, and memoize it. 2277 template mdFileCached() 2278 { 2279 import std.digest.md; 2280 alias mdFileCached = fileDigestCached!MD5; 2281 } 2282 2283 version (HAVE_WIN32) 2284 unittest 2285 { 2286 import std.digest : toHexString; 2287 write("test.txt", "Hello, world!"); 2288 scope(exit) remove("test.txt"); 2289 assert(mdFileCached("test.txt").toHexString() == "6CD3556DEB0DA54BCA060B4C39479839"); 2290 write("test.txt", "Something else"); 2291 assert(mdFileCached("test.txt").toHexString() == "6CD3556DEB0DA54BCA060B4C39479839"); 2292 } 2293 2294 /// Read a File (which might be a stream) into an array 2295 ubyte[] readFile(File f) 2296 { 2297 import std.range.primitives; 2298 auto result = appender!(ubyte[]); 2299 put(result, f.byChunk(64*1024)); 2300 return result.data; 2301 } 2302 2303 unittest 2304 { 2305 auto s = "0123456789".replicate(10_000); 2306 write("test.txt", s); 2307 scope(exit) remove("test.txt"); 2308 assert(readFile(File("test.txt")) == s); 2309 } 2310 2311 /// Read exactly `buf.length` bytes and return true. 2312 /// On EOF, return false. 2313 bool readExactly(File f, ubyte[] buf) 2314 { 2315 if (!buf.length) 2316 return true; 2317 auto read = f.rawRead(buf); 2318 if (read.length==0) return false; 2319 enforce(read.length == buf.length, "Unexpected end of file"); 2320 return true; 2321 } 2322 2323 private 2324 version (Windows) 2325 { 2326 version (CRuntime_DigitalMars) 2327 extern(C) sizediff_t read(int, void*, size_t); 2328 else 2329 { 2330 extern(C) sizediff_t _read(int, void*, size_t); 2331 alias read = _read; 2332 } 2333 } 2334 else 2335 import core.sys.posix.unistd : read; 2336 2337 /// Like `File.rawRead`, but returns as soon as any data is available. 2338 void[] readPartial(File f, void[] buf) 2339 { 2340 assert(buf.length); 2341 auto numRead = read(f.fileno, buf.ptr, buf.length); 2342 errnoEnforce(numRead >= 0); 2343 return buf[0 .. numRead]; 2344 } 2345 2346 /// Like std.file.readText for non-UTF8 2347 ascii readAscii()(string fileName) 2348 { 2349 return cast(ascii)readFile(openFile(fileName, "rb")); 2350 } 2351 2352 // https://issues.dlang.org/show_bug.cgi?id=7016 2353 version(Posix) static import ae.sys.signals; 2354 2355 /// Start a thread which writes data to f asynchronously. 2356 Thread writeFileAsync(File f, in void[] data) 2357 { 2358 static class Writer : Thread 2359 { 2360 File target; 2361 const void[] data; 2362 2363 this(ref File f, in void[] data) 2364 { 2365 this.target = f; 2366 this.data = data; 2367 super(&run); 2368 } 2369 2370 void run() 2371 { 2372 version (Posix) 2373 { 2374 import ae.sys.signals; 2375 collectSignal(SIGPIPE, &write); 2376 } 2377 else 2378 write(); 2379 } 2380 2381 void write() 2382 { 2383 target.rawWrite(data); 2384 target.close(); 2385 } 2386 } 2387 2388 auto t = new Writer(f, data); 2389 t.start(); 2390 return t; 2391 } 2392 2393 /// Start a thread which reads data from f asynchronously. 2394 /// Call the returning delegate to obtain the read data, 2395 /// blocking until the read completes. 2396 ubyte[] delegate() readFileAsync(File f) 2397 { 2398 static class Reader : Thread 2399 { 2400 File target; 2401 ubyte[] data; 2402 2403 this(ref File f) 2404 { 2405 this.target = f; 2406 this.data = data; 2407 super(&run); 2408 } 2409 2410 void run() 2411 { 2412 data = readFile(target); 2413 } 2414 } 2415 2416 auto t = new Reader(f); 2417 t.start(); 2418 return { 2419 t.join(); 2420 return t.data; 2421 }; 2422 } 2423 2424 /// Write data to a file, and ensure it gets written to disk 2425 /// before this function returns. 2426 /// Consider using as atomic!syncWrite. 2427 /// See also: syncUpdate 2428 void syncWrite()(string target, in void[] data) 2429 { 2430 auto f = File(target, "wb"); 2431 f.rawWrite(data); 2432 version (Windows) 2433 { 2434 mixin(importWin32!q{windows}); 2435 FlushFileBuffers(f.windowsHandle); 2436 } 2437 else 2438 { 2439 import core.sys.posix.unistd; 2440 fsync(f.fileno); 2441 } 2442 f.close(); 2443 } 2444 2445 /// Atomically save data to a file (if the file doesn't exist, 2446 /// or its contents differs). The update operation as a whole 2447 /// is not atomic, only the write is. 2448 void syncUpdate()(string fn, in void[] data) 2449 { 2450 if (!fn.exists || fn.read() != data) 2451 atomic!(syncWrite!())(fn, data); 2452 } 2453 2454 version(Windows) import ae.sys.windows.exception; 2455 2456 /// Create a named pipe, and allow interacting with it using a `std.stdio.File`. 2457 struct NamedPipeImpl 2458 { 2459 immutable string fileName; /// 2460 2461 /// Create a named pipe, and reserve a filename. 2462 this()(string name) 2463 { 2464 version(Windows) 2465 { 2466 mixin(importWin32!q{winbase}); 2467 2468 fileName = `\\.\pipe\` ~ name; 2469 auto h = CreateNamedPipeW(fileName.toUTF16z, PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE, 10, 4096, 4096, 0, null).wenforce("CreateNamedPipeW"); 2470 f.windowsHandleOpen(h, "wb"); 2471 } 2472 else 2473 { 2474 import core.sys.posix.sys.stat; 2475 2476 fileName = `/tmp/` ~ name ~ `.fifo`; 2477 mkfifo(fileName.toStringz, S_IWUSR | S_IRUSR); 2478 } 2479 } 2480 2481 /// Wait for a peer to open the other end of the pipe. 2482 File connect()() 2483 { 2484 version(Windows) 2485 { 2486 mixin(importWin32!q{winbase}); 2487 mixin(importWin32!q{windef}); 2488 2489 BOOL bSuccess = ConnectNamedPipe(f.windowsHandle, null); 2490 2491 // "If a client connects before the function is called, the function returns zero 2492 // and GetLastError returns ERROR_PIPE_CONNECTED. This can happen if a client 2493 // connects in the interval between the call to CreateNamedPipe and the call to 2494 // ConnectNamedPipe. In this situation, there is a good connection between client 2495 // and server, even though the function returns zero." 2496 if (!bSuccess) 2497 wenforce(GetLastError() == ERROR_PIPE_CONNECTED, "ConnectNamedPipe"); 2498 2499 return f; 2500 } 2501 else 2502 { 2503 return File(fileName, "w"); 2504 } 2505 } 2506 2507 ~this() 2508 { 2509 version(Windows) 2510 { 2511 // File.~this will take care of cleanup 2512 } 2513 else 2514 fileName.remove(); 2515 } 2516 2517 private: 2518 File f; 2519 } 2520 alias NamedPipe = RefCounted!NamedPipeImpl; /// ditto 2521 2522 import ae.utils.textout : StringBuilder; 2523 2524 /// Avoid std.stdio.File.readln's memory corruption bug 2525 /// https://issues.dlang.org/show_bug.cgi?id=13856 2526 string safeReadln(File f) 2527 { 2528 StringBuilder buf; 2529 char[1] arr; 2530 while (true) 2531 { 2532 auto result = f.rawRead(arr[]); 2533 if (!result.length) 2534 break; 2535 buf.put(result); 2536 if (result[0] == '\x0A') 2537 break; 2538 } 2539 return buf.get(); 2540 } 2541 2542 // **************************************************************************** 2543 2544 /// Change the current directory to the given directory. Does nothing if dir is null. 2545 /// Return a scope guard which, upon destruction, restores the previous directory. 2546 /// Asserts that only one thread has changed the process's current directory at any time. 2547 auto pushd(string dir) 2548 { 2549 import core.atomic; 2550 2551 static int threadCount = 0; 2552 static shared int processCount = 0; 2553 2554 static struct Popd 2555 { 2556 string oldPath; 2557 this(string cwd) { oldPath = cwd; } 2558 ~this() { if (oldPath) pop(); } 2559 @disable this(); 2560 @disable this(this); 2561 2562 void pop() 2563 { 2564 assert(oldPath); 2565 scope(exit) oldPath = null; 2566 chdir(oldPath); 2567 2568 auto newThreadCount = --threadCount; 2569 auto newProcessCount = atomicOp!"-="(processCount, 1); 2570 assert(newThreadCount == newProcessCount); // Shouldn't happen 2571 } 2572 } 2573 2574 string cwd; 2575 if (dir) 2576 { 2577 auto newThreadCount = ++threadCount; 2578 auto newProcessCount = atomicOp!"+="(processCount, 1); 2579 assert(newThreadCount == newProcessCount, "Another thread already has an active pushd"); 2580 2581 cwd = getcwd(); 2582 chdir(dir); 2583 } 2584 return Popd(cwd); 2585 } 2586 2587 // **************************************************************************** 2588 2589 import std.algorithm; 2590 import std.process : thisProcessID; 2591 import std.traits; 2592 import std.typetuple; 2593 import ae.utils.meta; 2594 2595 /// Parameter names that `atomic` assumes 2596 /// indicate a destination file by default. 2597 enum targetParameterNames = "target/to/name/dst"; 2598 2599 /// Wrap an operation which creates a file or directory, 2600 /// so that it is created safely and, for files, atomically 2601 /// (by performing the underlying operation to a temporary 2602 /// location, then renaming the completed file/directory to 2603 /// the actual target location). targetName specifies the name 2604 /// of the parameter containing the target file/directory. 2605 auto atomic(alias impl, string targetName = targetParameterNames)(staticMap!(Unqual, ParameterTypeTuple!impl) args) 2606 { 2607 enum targetIndex = findParameter([ParameterIdentifierTuple!impl], targetName, __traits(identifier, impl)); 2608 return atomic!(impl, targetIndex)(args); 2609 } 2610 2611 /// ditto 2612 auto atomic(alias impl, size_t targetIndex)(staticMap!(Unqual, ParameterTypeTuple!impl) args) 2613 { 2614 // idup for https://issues.dlang.org/show_bug.cgi?id=12503 2615 auto target = args[targetIndex].idup; 2616 auto temp = "%s.%s.%s.temp".format(target, thisProcessID, getCurrentThreadID); 2617 if (temp.exists) temp.removeRecurse(); 2618 scope(success) rename(temp, target); 2619 scope(failure) if (temp.exists) temp.removeRecurse(); 2620 args[targetIndex] = temp; 2621 return impl(args); 2622 } 2623 2624 /// ditto 2625 // Workaround for https://issues.dlang.org/show_bug.cgi?id=12230 2626 // Can't be an overload because of https://issues.dlang.org/show_bug.cgi?id=13374 2627 //R atomicDg(string targetName = "target", R, Args...)(R delegate(Args) impl, staticMap!(Unqual, Args) args) 2628 auto atomicDg(size_t targetIndexA = size_t.max, Impl, Args...)(Impl impl, Args args) 2629 { 2630 enum targetIndex = targetIndexA == size_t.max ? ParameterTypeTuple!impl.length-1 : targetIndexA; 2631 return atomic!(impl, targetIndex)(args); 2632 } 2633 2634 deprecated alias safeUpdate = atomic; 2635 2636 unittest 2637 { 2638 enum fn = "atomic.tmp"; 2639 scope(exit) if (fn.exists) fn.remove(); 2640 2641 atomic!touch(fn); 2642 assert(fn.exists); 2643 fn.remove(); 2644 2645 atomicDg(&touch, fn); 2646 assert(fn.exists); 2647 } 2648 2649 /// Wrap an operation so that it is skipped entirely 2650 /// if the target already exists. Implies atomic. 2651 auto cached(alias impl, string targetName = targetParameterNames)(ParameterTypeTuple!impl args) 2652 { 2653 enum targetIndex = findParameter([ParameterIdentifierTuple!impl], targetName, __traits(identifier, impl)); 2654 auto target = args[targetIndex]; 2655 if (!target.exists) 2656 atomic!(impl, targetIndex)(args); 2657 return target; 2658 } 2659 2660 /// ditto 2661 // Exists due to the same reasons as atomicDg 2662 auto cachedDg(size_t targetIndexA = size_t.max, Impl, Args...)(Impl impl, Args args) 2663 { 2664 enum targetIndex = targetIndexA == size_t.max ? ParameterTypeTuple!impl.length-1 : targetIndexA; 2665 auto target = args[targetIndex]; 2666 if (!target.exists) 2667 atomic!(impl, targetIndex)(args); 2668 return target; 2669 } 2670 2671 deprecated alias obtainUsing = cached; 2672 2673 /// Create a file, or replace an existing file's contents 2674 /// atomically. 2675 /// Note: Consider using atomic!syncWrite or 2676 /// atomic!syncUpdate instead. 2677 alias atomicWrite = atomic!_writeProxy; 2678 deprecated alias safeWrite = atomicWrite; 2679 /*private*/ void _writeProxy(string target, in void[] data) 2680 { 2681 std.file.write(target, data); 2682 } 2683 2684 // Work around for https://github.com/D-Programming-Language/phobos/pull/2784#issuecomment-68117241 2685 private void copy2(string source, string target) { std.file.copy(source, target); } 2686 2687 /// Copy a file, or replace an existing file's contents 2688 /// with another file's, atomically. 2689 alias atomic!copy2 atomicCopy; 2690 2691 unittest 2692 { 2693 enum fn = "cached.tmp"; 2694 scope(exit) if (fn.exists) fn.remove(); 2695 2696 cached!touch(fn); 2697 assert(fn.exists); 2698 2699 std.file.write(fn, "test"); 2700 2701 cachedDg!0(&_writeProxy, fn, "test2"); 2702 assert(fn.readText() == "test"); 2703 } 2704 2705 // **************************************************************************** 2706 2707 /// Composes a function which generates a file name 2708 /// with a function which creates the file. 2709 /// Returns the file name. 2710 template withTarget(alias targetGen, alias fun) 2711 { 2712 auto withTarget(Args...)(auto ref Args args) 2713 { 2714 auto target = targetGen(args); 2715 fun(args, target); 2716 return target; 2717 } 2718 } 2719 2720 /// Two-argument buildPath with reversed arguments. 2721 /// Useful for UFCS chaining. 2722 string prependPath(string target, string path) 2723 { 2724 return buildPath(path, target); 2725 }