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