2016-03-01 19:30:42 +00:00
|
|
|
/**
|
|
|
|
File handling functions and types.
|
|
|
|
|
2020-01-27 18:20:52 +00:00
|
|
|
Copyright: © 2012-2019 Sönke Ludwig
|
2016-03-01 19:30:42 +00:00
|
|
|
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
|
|
|
|
Authors: Sönke Ludwig
|
|
|
|
*/
|
|
|
|
module vibe.core.file;
|
|
|
|
|
2018-03-16 17:06:53 +00:00
|
|
|
import eventcore.core : NativeEventDriver, eventDriver;
|
2016-10-06 20:06:51 +00:00
|
|
|
import eventcore.driver;
|
2018-03-16 17:06:53 +00:00
|
|
|
import vibe.core.internal.release;
|
2016-10-06 20:06:51 +00:00
|
|
|
import vibe.core.log;
|
2016-03-01 19:30:42 +00:00
|
|
|
import vibe.core.path;
|
2016-10-26 11:11:28 +00:00
|
|
|
import vibe.core.stream;
|
2020-03-18 14:32:26 +00:00
|
|
|
import vibe.core.task : Task, TaskSettings;
|
2018-12-28 09:14:50 +00:00
|
|
|
import vibe.internal.async : asyncAwait, asyncAwaitUninterruptible;
|
2016-03-01 19:30:42 +00:00
|
|
|
|
|
|
|
import core.stdc.stdio;
|
|
|
|
import core.sys.posix.unistd;
|
|
|
|
import core.sys.posix.fcntl;
|
|
|
|
import core.sys.posix.sys.stat;
|
2018-12-23 21:22:53 +00:00
|
|
|
import core.time;
|
2016-03-01 19:30:42 +00:00
|
|
|
import std.conv : octal;
|
|
|
|
import std.datetime;
|
|
|
|
import std.exception;
|
|
|
|
import std.file;
|
|
|
|
import std.path;
|
|
|
|
import std.string;
|
2019-08-21 09:40:30 +00:00
|
|
|
import std.typecons : Flag, No;
|
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
|
|
|
|
version(Posix){
|
|
|
|
private extern(C) int mkstemps(char* templ, int suffixlen);
|
|
|
|
}
|
|
|
|
|
2016-11-02 19:54:43 +00:00
|
|
|
@safe:
|
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
Opens a file stream with the specified mode.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
FileStream openFile(NativePath path, FileMode mode = FileMode.read)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2017-05-30 08:57:31 +00:00
|
|
|
auto fil = eventDriver.files.open(path.toNativeString(), cast(FileOpenMode)mode);
|
|
|
|
enforce(fil != FileFD.invalid, "Failed to open file '"~path.toNativeString~"'");
|
|
|
|
return FileStream(fil, path, mode);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
FileStream openFile(string path, FileMode mode = FileMode.read)
|
|
|
|
{
|
2017-06-19 22:37:56 +00:00
|
|
|
return openFile(NativePath(path), mode);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
Read a whole file into a buffer.
|
|
|
|
|
|
|
|
If the supplied buffer is large enough, it will be used to store the
|
|
|
|
contents of the file. Otherwise, a new buffer will be allocated.
|
|
|
|
|
|
|
|
Params:
|
|
|
|
path = The path of the file to read
|
|
|
|
buffer = An optional buffer to use for storing the file contents
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
ubyte[] readFile(NativePath path, ubyte[] buffer = null, size_t max_size = size_t.max)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
|
|
|
auto fil = openFile(path);
|
|
|
|
scope (exit) fil.close();
|
|
|
|
enforce(fil.size <= max_size, "File is too big.");
|
|
|
|
auto sz = cast(size_t)fil.size;
|
|
|
|
auto ret = sz <= buffer.length ? buffer[0 .. sz] : new ubyte[sz];
|
|
|
|
fil.read(ret);
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
ubyte[] readFile(string path, ubyte[] buffer = null, size_t max_size = size_t.max)
|
|
|
|
{
|
2017-06-19 22:37:56 +00:00
|
|
|
return readFile(NativePath(path), buffer, max_size);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
Write a whole file at once.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
void writeFile(NativePath path, in ubyte[] contents)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
|
|
|
auto fil = openFile(path, FileMode.createTrunc);
|
|
|
|
scope (exit) fil.close();
|
|
|
|
fil.write(contents);
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
void writeFile(string path, in ubyte[] contents)
|
|
|
|
{
|
2017-06-19 22:37:56 +00:00
|
|
|
writeFile(NativePath(path), contents);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Convenience function to append to a file.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
void appendToFile(NativePath path, string data) {
|
2016-03-01 19:30:42 +00:00
|
|
|
auto fil = openFile(path, FileMode.append);
|
|
|
|
scope(exit) fil.close();
|
|
|
|
fil.write(data);
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
void appendToFile(string path, string data)
|
|
|
|
{
|
2017-06-19 22:37:56 +00:00
|
|
|
appendToFile(NativePath(path), data);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Read a whole UTF-8 encoded file into a string.
|
|
|
|
|
|
|
|
The resulting string will be sanitized and will have the
|
|
|
|
optional byte order mark (BOM) removed.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
string readFileUTF8(NativePath path)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
|
|
|
import vibe.internal.string;
|
|
|
|
|
2019-10-22 09:41:35 +00:00
|
|
|
auto data = readFile(path);
|
|
|
|
auto idata = () @trusted { return data.assumeUnique; } ();
|
|
|
|
return stripUTF8Bom(sanitizeUTF8(idata));
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
string readFileUTF8(string path)
|
|
|
|
{
|
2017-06-19 22:37:56 +00:00
|
|
|
return readFileUTF8(NativePath(path));
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
Write a string into a UTF-8 encoded file.
|
|
|
|
|
|
|
|
The file will have a byte order mark (BOM) prepended.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
void writeFileUTF8(NativePath path, string contents)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
|
|
|
static immutable ubyte[] bom = [0xEF, 0xBB, 0xBF];
|
|
|
|
auto fil = openFile(path, FileMode.createTrunc);
|
|
|
|
scope (exit) fil.close();
|
|
|
|
fil.write(bom);
|
|
|
|
fil.write(contents);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Creates and opens a temporary file for writing.
|
|
|
|
*/
|
|
|
|
FileStream createTempFile(string suffix = null)
|
|
|
|
{
|
|
|
|
version(Windows){
|
|
|
|
import std.conv : to;
|
2016-12-19 15:16:50 +00:00
|
|
|
string tmpname;
|
|
|
|
() @trusted {
|
2017-03-09 15:09:46 +00:00
|
|
|
auto fn = tmpnam(null);
|
|
|
|
enforce(fn !is null, "Failed to generate temporary name.");
|
|
|
|
tmpname = to!string(fn);
|
2016-12-19 15:16:50 +00:00
|
|
|
} ();
|
|
|
|
if (tmpname.startsWith("\\")) tmpname = tmpname[1 .. $];
|
2016-03-01 19:30:42 +00:00
|
|
|
tmpname ~= suffix;
|
|
|
|
return openFile(tmpname, FileMode.createTrunc);
|
|
|
|
} else {
|
|
|
|
enum pattern ="/tmp/vtmp.XXXXXX";
|
|
|
|
scope templ = new char[pattern.length+suffix.length+1];
|
|
|
|
templ[0 .. pattern.length] = pattern;
|
|
|
|
templ[pattern.length .. $-1] = (suffix)[];
|
|
|
|
templ[$-1] = '\0';
|
|
|
|
assert(suffix.length <= int.max);
|
2016-11-02 19:54:43 +00:00
|
|
|
auto fd = () @trusted { return mkstemps(templ.ptr, cast(int)suffix.length); } ();
|
2016-03-01 19:30:42 +00:00
|
|
|
enforce(fd >= 0, "Failed to create temporary file.");
|
2016-12-10 15:01:40 +00:00
|
|
|
auto efd = eventDriver.files.adopt(fd);
|
2017-06-19 22:37:56 +00:00
|
|
|
return FileStream(efd, NativePath(templ[0 .. $-1].idup), FileMode.createTrunc);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Moves or renames a file.
|
|
|
|
|
|
|
|
Params:
|
|
|
|
from = Path to the file/directory to move/rename.
|
|
|
|
to = The target path
|
|
|
|
copy_fallback = Determines if copy/remove should be used in case of the
|
|
|
|
source and destination path pointing to different devices.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
void moveFile(NativePath from, NativePath to, bool copy_fallback = false)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
|
|
|
moveFile(from.toNativeString(), to.toNativeString(), copy_fallback);
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
void moveFile(string from, string to, bool copy_fallback = false)
|
|
|
|
{
|
2020-05-17 13:10:01 +00:00
|
|
|
auto fail = performInWorker((string from, string to) {
|
2016-03-01 19:30:42 +00:00
|
|
|
try {
|
|
|
|
std.file.rename(from, to);
|
2020-05-17 13:10:01 +00:00
|
|
|
} catch (Exception e) {
|
|
|
|
return e.msg.length ? e.msg : "Failed to move file.";
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
2020-05-17 13:10:01 +00:00
|
|
|
return null;
|
|
|
|
}, from, to);
|
|
|
|
|
|
|
|
if (!fail.length) return;
|
|
|
|
|
|
|
|
if (!copy_fallback) throw new Exception(fail);
|
|
|
|
|
|
|
|
copyFile(from, to);
|
|
|
|
removeFile(from);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Copies a file.
|
|
|
|
|
|
|
|
Note that attributes and time stamps are currently not retained.
|
|
|
|
|
|
|
|
Params:
|
|
|
|
from = Path of the source file
|
|
|
|
to = Path for the destination file
|
|
|
|
overwrite = If true, any file existing at the destination path will be
|
|
|
|
overwritten. If this is false, an exception will be thrown should
|
|
|
|
a file already exist at the destination path.
|
|
|
|
|
|
|
|
Throws:
|
|
|
|
An Exception if the copy operation fails for some reason.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
void copyFile(NativePath from, NativePath to, bool overwrite = false)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2019-01-13 23:32:27 +00:00
|
|
|
DirEntry info;
|
|
|
|
static if (__VERSION__ < 2078) {
|
|
|
|
() @trusted {
|
|
|
|
info = DirEntry(from.toString);
|
|
|
|
enforce(info.isFile, "The source path is not a file and cannot be copied.");
|
|
|
|
} ();
|
|
|
|
} else {
|
|
|
|
info = DirEntry(from.toString);
|
|
|
|
enforce(info.isFile, "The source path is not a file and cannot be copied.");
|
|
|
|
}
|
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
|
|
|
auto src = openFile(from, FileMode.read);
|
|
|
|
scope(exit) src.close();
|
|
|
|
enforce(overwrite || !existsFile(to), "Destination file already exists.");
|
|
|
|
auto dst = openFile(to, FileMode.createTrunc);
|
|
|
|
scope(exit) dst.close();
|
2020-05-17 13:10:01 +00:00
|
|
|
dst.truncate(src.size);
|
2020-10-21 14:58:03 +00:00
|
|
|
src.pipe(dst, PipeMode.concurrent);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
2019-01-13 23:32:27 +00:00
|
|
|
// TODO: also retain creation time on windows
|
|
|
|
|
|
|
|
static if (__VERSION__ < 2078) {
|
|
|
|
() @trusted {
|
|
|
|
setTimes(to.toString, info.timeLastAccessed, info.timeLastModified);
|
2019-06-16 08:12:02 +00:00
|
|
|
setAttributes(to.toString, info.attributes);
|
2019-01-13 23:32:27 +00:00
|
|
|
} ();
|
|
|
|
} else {
|
|
|
|
setTimes(to.toString, info.timeLastAccessed, info.timeLastModified);
|
2019-06-16 08:12:02 +00:00
|
|
|
setAttributes(to.toString, info.attributes);
|
2019-01-13 23:32:27 +00:00
|
|
|
}
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
void copyFile(string from, string to)
|
|
|
|
{
|
2017-06-19 22:37:56 +00:00
|
|
|
copyFile(NativePath(from), NativePath(to));
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Removes a file
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
void removeFile(NativePath path)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
|
|
|
removeFile(path.toNativeString());
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
void removeFile(string path)
|
|
|
|
{
|
2020-05-17 13:10:01 +00:00
|
|
|
auto fail = performInWorker((string path) {
|
|
|
|
try {
|
|
|
|
std.file.remove(path);
|
|
|
|
} catch (Exception e) {
|
|
|
|
return e.msg.length ? e.msg : "Failed to delete file.";
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}, path);
|
|
|
|
|
|
|
|
if (fail.length) throw new Exception(fail);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Checks if a file exists
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
bool existsFile(NativePath path) nothrow
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
|
|
|
return existsFile(path.toNativeString());
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
bool existsFile(string path) nothrow
|
|
|
|
{
|
|
|
|
// This was *annotated* nothrow in 2.067.
|
|
|
|
static if (__VERSION__ < 2067)
|
|
|
|
scope(failure) assert(0, "Error: existsFile should never throw");
|
2019-08-21 09:40:30 +00:00
|
|
|
|
2019-08-25 10:02:08 +00:00
|
|
|
try return performInWorker((string p) => std.file.exists(p), path);
|
2019-08-21 09:40:30 +00:00
|
|
|
catch (Exception e) {
|
|
|
|
logDebug("Failed to determine file existence for '%s': %s", path, e.msg);
|
|
|
|
return false;
|
|
|
|
}
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Stores information about the specified file/directory into 'info'
|
|
|
|
|
|
|
|
Throws: A `FileException` is thrown if the file does not exist.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
FileInfo getFileInfo(NativePath path)
|
2016-11-02 19:54:43 +00:00
|
|
|
@trusted {
|
2019-08-21 09:40:30 +00:00
|
|
|
return getFileInfo(path.toNativeString);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
FileInfo getFileInfo(string path)
|
|
|
|
{
|
2019-08-25 10:02:08 +00:00
|
|
|
import std.typecons : tuple;
|
|
|
|
|
|
|
|
auto ret = performInWorker((string p) {
|
|
|
|
try {
|
|
|
|
auto ent = DirEntry(p);
|
|
|
|
return tuple(makeFileInfo(ent), "");
|
|
|
|
} catch (Exception e) {
|
|
|
|
return tuple(FileInfo.init, e.msg.length ? e.msg : "Failed to get file information");
|
|
|
|
}
|
|
|
|
}, path);
|
|
|
|
if (ret[1].length) throw new Exception(ret[1]);
|
|
|
|
return ret[0];
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Creates a new directory.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
void createDirectory(NativePath path)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2019-08-21 09:40:30 +00:00
|
|
|
createDirectory(path.toNativeString);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
/// ditto
|
2019-08-21 09:40:30 +00:00
|
|
|
void createDirectory(string path, Flag!"recursive" recursive = No.recursive)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2019-08-25 10:02:08 +00:00
|
|
|
auto fail = performInWorker((string p, bool rec) {
|
2019-08-21 09:40:30 +00:00
|
|
|
try {
|
|
|
|
if (rec) mkdirRecurse(p);
|
|
|
|
else mkdir(p);
|
|
|
|
} catch (Exception e) {
|
|
|
|
return e.msg.length ? e.msg : "Failed to create directory.";
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}, path, !!recursive);
|
|
|
|
|
|
|
|
if (fail) throw new Exception(fail);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Enumerates all files in the specified directory.
|
|
|
|
*/
|
2021-01-12 09:06:16 +00:00
|
|
|
void listDirectory(NativePath path, DirectoryListMode mode,
|
|
|
|
scope bool delegate(FileInfo info) @safe del)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2021-01-12 09:06:16 +00:00
|
|
|
import vibe.core.channel : ChannelConfig, ChannelPriority, createChannel;
|
|
|
|
import vibe.core.core : runWorkerTask;
|
2019-08-21 09:40:30 +00:00
|
|
|
|
2021-01-12 09:06:16 +00:00
|
|
|
ChannelConfig cc;
|
|
|
|
cc.priority = ChannelPriority.overhead;
|
2019-08-21 09:40:30 +00:00
|
|
|
|
2021-01-12 09:06:16 +00:00
|
|
|
ListDirectoryRequest req;
|
|
|
|
req.path = path;
|
|
|
|
req.channel = createChannel!ListDirectoryData(cc);
|
|
|
|
req.spanMode = mode;
|
2019-08-21 09:40:30 +00:00
|
|
|
|
2021-01-12 09:06:16 +00:00
|
|
|
runWorkerTask(ioTaskSettings, &performListDirectory, req);
|
2020-12-01 18:23:05 +00:00
|
|
|
|
2021-01-12 09:06:16 +00:00
|
|
|
ListDirectoryData itm;
|
|
|
|
while (req.channel.tryConsumeOne(itm)) {
|
2019-08-21 09:40:30 +00:00
|
|
|
if (itm.error.length)
|
|
|
|
throw new Exception(itm.error);
|
|
|
|
|
|
|
|
if (!del(itm.info)) {
|
2021-01-12 09:06:16 +00:00
|
|
|
req.channel.close();
|
|
|
|
// makes sure that the directory handle is closed before returning
|
|
|
|
while (!req.channel.empty) req.channel.tryConsumeOne(itm);
|
2019-08-21 09:40:30 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/// ditto
|
2021-01-12 09:06:16 +00:00
|
|
|
void listDirectory(string path, DirectoryListMode mode,
|
|
|
|
scope bool delegate(FileInfo info) @safe del)
|
|
|
|
{
|
|
|
|
listDirectory(NativePath(path), mode, del);
|
|
|
|
}
|
|
|
|
void listDirectory(NativePath path, scope bool delegate(FileInfo info) @safe del)
|
|
|
|
{
|
|
|
|
listDirectory(path, DirectoryListMode.shallow, del);
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
void listDirectory(string path, scope bool delegate(FileInfo info) @safe del)
|
|
|
|
{
|
|
|
|
listDirectory(path, DirectoryListMode.shallow, del);
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
void listDirectory(NativePath path, DirectoryListMode mode, scope bool delegate(FileInfo info) @system del)
|
|
|
|
@system {
|
|
|
|
listDirectory(path, mode, (nfo) @trusted => del(nfo));
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
void listDirectory(string path, DirectoryListMode mode, scope bool delegate(FileInfo info) @system del)
|
|
|
|
@system {
|
|
|
|
listDirectory(path, mode, (nfo) @trusted => del(nfo));
|
|
|
|
}
|
|
|
|
/// ditto
|
2019-08-21 09:40:30 +00:00
|
|
|
void listDirectory(NativePath path, scope bool delegate(FileInfo info) @system del)
|
|
|
|
@system {
|
|
|
|
listDirectory(path, (nfo) @trusted => del(nfo));
|
|
|
|
}
|
|
|
|
/// ditto
|
|
|
|
void listDirectory(string path, scope bool delegate(FileInfo info) @system del)
|
|
|
|
@system {
|
|
|
|
listDirectory(path, (nfo) @trusted => del(nfo));
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
/// ditto
|
2021-01-12 09:06:16 +00:00
|
|
|
int delegate(scope int delegate(ref FileInfo)) iterateDirectory(NativePath path,
|
|
|
|
DirectoryListMode mode = DirectoryListMode.shallow)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
|
|
|
int iterator(scope int delegate(ref FileInfo) del){
|
|
|
|
int ret = 0;
|
2021-01-12 09:06:16 +00:00
|
|
|
listDirectory(path, mode, (fi) {
|
2016-03-01 19:30:42 +00:00
|
|
|
ret = del(fi);
|
|
|
|
return ret == 0;
|
|
|
|
});
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
return &iterator;
|
|
|
|
}
|
|
|
|
/// ditto
|
2021-01-12 09:06:16 +00:00
|
|
|
int delegate(scope int delegate(ref FileInfo)) iterateDirectory(string path,
|
|
|
|
DirectoryListMode mode = DirectoryListMode.shallow)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2021-01-12 09:06:16 +00:00
|
|
|
return iterateDirectory(NativePath(path), mode);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Starts watching a directory for changes.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
DirectoryWatcher watchDirectory(NativePath path, bool recursive = true)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2016-10-25 06:57:16 +00:00
|
|
|
return DirectoryWatcher(path, recursive);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
// ditto
|
|
|
|
DirectoryWatcher watchDirectory(string path, bool recursive = true)
|
|
|
|
{
|
2017-06-19 22:37:56 +00:00
|
|
|
return watchDirectory(NativePath(path), recursive);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Returns the current working directory.
|
|
|
|
*/
|
2017-06-19 22:37:56 +00:00
|
|
|
NativePath getWorkingDirectory()
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2017-06-19 22:37:56 +00:00
|
|
|
return NativePath(() @trusted { return std.file.getcwd(); } ());
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** Contains general information about a file.
|
|
|
|
*/
|
|
|
|
struct FileInfo {
|
|
|
|
/// Name of the file (not including the path)
|
|
|
|
string name;
|
|
|
|
|
2021-01-12 09:06:16 +00:00
|
|
|
/// The directory containing the file
|
|
|
|
NativePath directory;
|
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
/// Size of the file (zero for directories)
|
|
|
|
ulong size;
|
|
|
|
|
|
|
|
/// Time of the last modification
|
|
|
|
SysTime timeModified;
|
|
|
|
|
|
|
|
/// Time of creation (not available on all operating systems/file systems)
|
|
|
|
SysTime timeCreated;
|
|
|
|
|
|
|
|
/// True if this is a symlink to an actual file
|
|
|
|
bool isSymlink;
|
|
|
|
|
|
|
|
/// True if this is a directory or a symlink pointing to a directory
|
|
|
|
bool isDirectory;
|
2017-11-07 15:14:02 +00:00
|
|
|
|
2019-03-21 16:39:44 +00:00
|
|
|
/// True if this is a file. On POSIX if both isFile and isDirectory are false it is a special file.
|
|
|
|
bool isFile;
|
|
|
|
|
2017-11-07 15:14:02 +00:00
|
|
|
/** True if the file's hidden attribute is set.
|
|
|
|
|
|
|
|
On systems that don't support a hidden attribute, any file starting with
|
|
|
|
a single dot will be treated as hidden.
|
|
|
|
*/
|
|
|
|
bool hidden;
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Specifies how a file is manipulated on disk.
|
|
|
|
*/
|
|
|
|
enum FileMode {
|
|
|
|
/// The file is opened read-only.
|
2016-10-06 20:06:51 +00:00
|
|
|
read = FileOpenMode.read,
|
2016-03-01 19:30:42 +00:00
|
|
|
/// The file is opened for read-write random access.
|
2016-10-06 20:06:51 +00:00
|
|
|
readWrite = FileOpenMode.readWrite,
|
2016-03-01 19:30:42 +00:00
|
|
|
/// The file is truncated if it exists or created otherwise and then opened for read-write access.
|
2016-10-06 20:06:51 +00:00
|
|
|
createTrunc = FileOpenMode.createTrunc,
|
2016-03-01 19:30:42 +00:00
|
|
|
/// The file is opened for appending data to it and created if it does not exist.
|
2016-10-06 20:06:51 +00:00
|
|
|
append = FileOpenMode.append
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
2021-01-12 09:06:16 +00:00
|
|
|
enum DirectoryListMode {
|
|
|
|
/// Only iterate the directory itself
|
2021-01-12 16:24:28 +00:00
|
|
|
shallow = 0,
|
|
|
|
/// Only iterate over directories directly within the given directory
|
|
|
|
shallowDirectories = 1<<1,
|
2021-01-12 09:06:16 +00:00
|
|
|
/// Iterate recursively (depth-first, pre-order)
|
2021-01-12 16:24:28 +00:00
|
|
|
recursive = 1<<0,
|
2021-01-12 09:06:16 +00:00
|
|
|
/// Iterate only directories recursively (depth-first, pre-order)
|
2021-01-12 16:24:28 +00:00
|
|
|
recursiveDirectories = recursive | shallowDirectories,
|
2021-01-12 09:06:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
/**
|
|
|
|
Accesses the contents of a file as a stream.
|
|
|
|
*/
|
|
|
|
struct FileStream {
|
2016-11-02 19:54:43 +00:00
|
|
|
@safe:
|
|
|
|
|
2016-12-26 20:28:36 +00:00
|
|
|
private struct CTX {
|
2017-06-19 22:37:56 +00:00
|
|
|
NativePath path;
|
2016-12-26 20:28:36 +00:00
|
|
|
ulong size;
|
|
|
|
FileMode mode;
|
|
|
|
ulong ptr;
|
2018-03-16 17:06:53 +00:00
|
|
|
shared(NativeEventDriver) driver;
|
2016-12-26 20:28:36 +00:00
|
|
|
}
|
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
private {
|
2016-10-06 20:06:51 +00:00
|
|
|
FileFD m_fd;
|
2016-12-26 20:28:36 +00:00
|
|
|
CTX* m_ctx;
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
2017-06-19 22:37:56 +00:00
|
|
|
private this(FileFD fd, NativePath path, FileMode mode)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2017-05-30 08:57:31 +00:00
|
|
|
assert(fd != FileFD.invalid, "Constructing FileStream from invalid file descriptor.");
|
2016-10-06 20:06:51 +00:00
|
|
|
m_fd = fd;
|
2016-12-26 20:28:36 +00:00
|
|
|
m_ctx = new CTX; // TODO: use FD custom storage
|
|
|
|
m_ctx.path = path;
|
|
|
|
m_ctx.mode = mode;
|
|
|
|
m_ctx.size = eventDriver.files.getSize(fd);
|
2018-03-16 17:06:53 +00:00
|
|
|
m_ctx.driver = () @trusted { return cast(shared)eventDriver; } ();
|
2019-07-19 23:34:27 +00:00
|
|
|
|
|
|
|
if (mode == FileMode.append)
|
|
|
|
m_ctx.ptr = m_ctx.size;
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
2016-10-06 20:15:25 +00:00
|
|
|
this(this)
|
|
|
|
{
|
2016-11-02 19:54:43 +00:00
|
|
|
if (m_fd != FileFD.invalid)
|
2016-10-06 20:15:25 +00:00
|
|
|
eventDriver.files.addRef(m_fd);
|
|
|
|
}
|
2017-07-02 21:54:30 +00:00
|
|
|
|
2016-10-06 20:15:25 +00:00
|
|
|
~this()
|
|
|
|
{
|
2016-11-02 19:54:43 +00:00
|
|
|
if (m_fd != FileFD.invalid)
|
2018-03-16 17:06:53 +00:00
|
|
|
releaseHandle!"files"(m_fd, m_ctx.driver);
|
2016-10-06 20:15:25 +00:00
|
|
|
}
|
2016-03-01 19:30:42 +00:00
|
|
|
|
2017-01-25 20:04:13 +00:00
|
|
|
@property int fd() { return cast(int)m_fd; }
|
2016-03-01 19:30:42 +00:00
|
|
|
|
|
|
|
/// The path of the file.
|
2017-06-19 22:37:56 +00:00
|
|
|
@property NativePath path() const { return ctx.path; }
|
2016-03-01 19:30:42 +00:00
|
|
|
|
|
|
|
/// Determines if the file stream is still open
|
2016-11-02 19:54:43 +00:00
|
|
|
@property bool isOpen() const { return m_fd != FileFD.invalid; }
|
2016-12-26 20:28:36 +00:00
|
|
|
@property ulong size() const nothrow { return ctx.size; }
|
|
|
|
@property bool readable() const nothrow { return ctx.mode != FileMode.append; }
|
|
|
|
@property bool writable() const nothrow { return ctx.mode != FileMode.read; }
|
2016-11-02 19:54:43 +00:00
|
|
|
|
|
|
|
bool opCast(T)() if (is (T == bool)) { return m_fd != FileFD.invalid; }
|
2016-03-01 19:30:42 +00:00
|
|
|
|
|
|
|
void takeOwnershipOfFD()
|
|
|
|
{
|
2016-10-06 20:06:51 +00:00
|
|
|
assert(false, "TODO!");
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void seek(ulong offset)
|
|
|
|
{
|
2019-07-25 22:27:50 +00:00
|
|
|
enforce(ctx.mode != FileMode.append, "File opened for appending, not random access. Cannot seek.");
|
2016-12-26 20:28:36 +00:00
|
|
|
ctx.ptr = offset;
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
2016-12-26 20:28:36 +00:00
|
|
|
ulong tell() nothrow { return ctx.ptr; }
|
2016-03-01 19:30:42 +00:00
|
|
|
|
2018-12-28 09:14:50 +00:00
|
|
|
void truncate(ulong size)
|
|
|
|
{
|
2019-07-25 22:27:50 +00:00
|
|
|
enforce(ctx.mode != FileMode.append, "File opened for appending, not random access. Cannot truncate.");
|
|
|
|
|
2018-12-28 09:14:50 +00:00
|
|
|
auto res = asyncAwaitUninterruptible!(FileIOCallback,
|
|
|
|
cb => eventDriver.files.truncate(m_fd, size, cb)
|
|
|
|
);
|
|
|
|
enforce(res[1] == IOStatus.ok, "Failed to resize file.");
|
|
|
|
m_ctx.size = size;
|
|
|
|
}
|
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
/// Closes the file handle.
|
|
|
|
void close()
|
|
|
|
{
|
2020-05-17 13:10:01 +00:00
|
|
|
if (m_fd == FileFD.invalid) return;
|
|
|
|
if (!eventDriver.files.isValid(m_fd)) return;
|
|
|
|
|
|
|
|
auto res = asyncAwaitUninterruptible!(FileCloseCallback,
|
|
|
|
cb => eventDriver.files.close(m_fd, cb)
|
|
|
|
);
|
|
|
|
releaseHandle!"files"(m_fd, m_ctx.driver);
|
|
|
|
m_fd = FileFD.invalid;
|
|
|
|
m_ctx = null;
|
|
|
|
|
|
|
|
if (res[1] != CloseStatus.ok)
|
|
|
|
throw new Exception("Failed to close file");
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
2016-12-26 20:28:36 +00:00
|
|
|
@property bool empty() const { assert(this.readable); return ctx.ptr >= ctx.size; }
|
|
|
|
@property ulong leastSize() const { assert(this.readable); return ctx.size - ctx.ptr; }
|
2016-03-01 19:30:42 +00:00
|
|
|
@property bool dataAvailableForRead() { return true; }
|
|
|
|
|
|
|
|
const(ubyte)[] peek()
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2017-01-18 23:36:32 +00:00
|
|
|
size_t read(ubyte[] dst, IOMode mode)
|
2017-02-16 22:37:14 +00:00
|
|
|
{
|
2020-09-18 08:00:30 +00:00
|
|
|
// NOTE: cancelRead is currently not behaving as specified and cannot
|
|
|
|
// be relied upon. For this reason, we MUST use the uninterruptible
|
|
|
|
// version of asyncAwait here!
|
|
|
|
auto res = asyncAwaitUninterruptible!(FileIOCallback,
|
|
|
|
cb => eventDriver.files.read(m_fd, ctx.ptr, dst, mode, cb)
|
2016-10-06 20:06:51 +00:00
|
|
|
);
|
2017-02-16 22:37:14 +00:00
|
|
|
ctx.ptr += res[2];
|
2016-10-06 20:06:51 +00:00
|
|
|
enforce(res[1] == IOStatus.ok, "Failed to read data from disk.");
|
2017-01-18 23:36:32 +00:00
|
|
|
return res[2];
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
2017-01-18 23:36:32 +00:00
|
|
|
void read(ubyte[] dst)
|
|
|
|
{
|
|
|
|
auto ret = read(dst, IOMode.all);
|
2017-10-30 21:55:22 +00:00
|
|
|
assert(ret == dst.length, "File.read returned less data than requested for IOMode.all.");
|
2017-01-18 23:36:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
size_t write(in ubyte[] bytes, IOMode mode)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2020-09-18 08:00:30 +00:00
|
|
|
// NOTE: cancelWrite is currently not behaving as specified and cannot
|
|
|
|
// be relied upon. For this reason, we MUST use the uninterruptible
|
|
|
|
// version of asyncAwait here!
|
|
|
|
auto res = asyncAwaitUninterruptible!(FileIOCallback,
|
|
|
|
cb => eventDriver.files.write(m_fd, ctx.ptr, bytes, mode, cb)
|
2016-10-06 20:06:51 +00:00
|
|
|
);
|
2016-12-26 20:28:36 +00:00
|
|
|
ctx.ptr += res[2];
|
|
|
|
if (ctx.ptr > ctx.size) ctx.size = ctx.ptr;
|
2019-01-06 23:26:16 +00:00
|
|
|
enforce(res[1] == IOStatus.ok, "Failed to write data to disk.");
|
2017-01-18 23:36:32 +00:00
|
|
|
return res[2];
|
|
|
|
}
|
|
|
|
|
|
|
|
void write(in ubyte[] bytes)
|
|
|
|
{
|
|
|
|
write(bytes, IOMode.all);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
2016-12-10 15:01:40 +00:00
|
|
|
void write(in char[] bytes)
|
|
|
|
{
|
|
|
|
write(cast(const(ubyte)[])bytes);
|
|
|
|
}
|
|
|
|
|
2017-01-25 20:04:13 +00:00
|
|
|
void write(InputStream)(InputStream stream, ulong nbytes = ulong.max)
|
2016-12-10 15:01:40 +00:00
|
|
|
if (isInputStream!InputStream)
|
2016-03-01 19:30:42 +00:00
|
|
|
{
|
2020-10-21 14:58:03 +00:00
|
|
|
pipe(stream, this, nbytes, PipeMode.concurrent);
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void flush()
|
|
|
|
{
|
|
|
|
assert(this.writable);
|
|
|
|
}
|
|
|
|
|
|
|
|
void finalize()
|
|
|
|
{
|
|
|
|
flush();
|
|
|
|
}
|
2016-12-26 20:28:36 +00:00
|
|
|
|
|
|
|
private inout(CTX)* ctx() inout nothrow { return m_ctx; }
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
2016-10-26 11:11:28 +00:00
|
|
|
mixin validateRandomAccessStream!FileStream;
|
|
|
|
|
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
/**
|
|
|
|
Interface for directory watcher implementations.
|
|
|
|
|
|
|
|
Directory watchers monitor the contents of a directory (wither recursively or non-recursively)
|
|
|
|
for changes, such as file additions, deletions or modifications.
|
|
|
|
*/
|
2016-10-25 06:57:16 +00:00
|
|
|
struct DirectoryWatcher { // TODO: avoid all those heap allocations!
|
|
|
|
import std.array : Appender, appender;
|
2017-07-20 14:42:58 +00:00
|
|
|
import vibe.core.sync : LocalManualEvent, createManualEvent;
|
2016-10-25 06:57:16 +00:00
|
|
|
|
|
|
|
@safe:
|
|
|
|
|
2017-01-29 21:11:17 +00:00
|
|
|
private static struct Context {
|
2017-06-19 22:37:56 +00:00
|
|
|
NativePath path;
|
2016-10-25 06:57:16 +00:00
|
|
|
bool recursive;
|
|
|
|
Appender!(DirectoryChange[]) changes;
|
2017-01-13 21:24:18 +00:00
|
|
|
LocalManualEvent changeEvent;
|
2018-03-16 17:06:53 +00:00
|
|
|
shared(NativeEventDriver) driver;
|
2017-01-29 21:11:17 +00:00
|
|
|
|
2020-08-31 02:17:55 +00:00
|
|
|
// Support for `-preview=in`
|
|
|
|
static if (!is(typeof(mixin(q{(in ref int a) => a}))))
|
|
|
|
{
|
|
|
|
void onChange(WatcherID id, in FileChange change) nothrow {
|
|
|
|
this.onChangeImpl(id, change);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
mixin(q{
|
|
|
|
void onChange(WatcherID id, in ref FileChange change) nothrow {
|
|
|
|
this.onChangeImpl(id, change);
|
|
|
|
}});
|
|
|
|
}
|
|
|
|
|
|
|
|
void onChangeImpl(WatcherID, const scope ref FileChange change)
|
2017-01-29 21:11:17 +00:00
|
|
|
nothrow {
|
|
|
|
DirectoryChangeType ct;
|
|
|
|
final switch (change.kind) {
|
|
|
|
case FileChangeKind.added: ct = DirectoryChangeType.added; break;
|
|
|
|
case FileChangeKind.removed: ct = DirectoryChangeType.removed; break;
|
|
|
|
case FileChangeKind.modified: ct = DirectoryChangeType.modified; break;
|
|
|
|
}
|
2017-11-21 20:42:44 +00:00
|
|
|
|
|
|
|
static if (is(typeof(change.baseDirectory))) {
|
|
|
|
// eventcore 0.8.23 and up
|
|
|
|
this.changes ~= DirectoryChange(ct, NativePath.fromTrustedString(change.baseDirectory) ~ NativePath.fromTrustedString(change.directory) ~ NativePath.fromTrustedString(change.name.idup));
|
|
|
|
} else {
|
|
|
|
this.changes ~= DirectoryChange(ct, NativePath.fromTrustedString(change.directory) ~ NativePath.fromTrustedString(change.name.idup));
|
|
|
|
}
|
2017-01-29 21:11:17 +00:00
|
|
|
this.changeEvent.emit();
|
|
|
|
}
|
2016-10-25 06:57:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private {
|
|
|
|
WatcherID m_watcher;
|
2017-01-29 21:11:17 +00:00
|
|
|
Context* m_context;
|
2016-10-25 06:57:16 +00:00
|
|
|
}
|
|
|
|
|
2017-06-19 22:37:56 +00:00
|
|
|
private this(NativePath path, bool recursive)
|
2016-10-25 06:57:16 +00:00
|
|
|
{
|
2017-01-29 21:11:17 +00:00
|
|
|
m_context = new Context; // FIME: avoid GC allocation (use FD user data slot)
|
2017-07-20 14:42:58 +00:00
|
|
|
m_context.changeEvent = createManualEvent();
|
2017-01-29 21:11:17 +00:00
|
|
|
m_watcher = eventDriver.watchers.watchDirectory(path.toNativeString, recursive, &m_context.onChange);
|
2019-07-25 22:20:53 +00:00
|
|
|
enforce(m_watcher != WatcherID.invalid, "Failed to watch directory.");
|
2016-10-25 06:57:16 +00:00
|
|
|
m_context.path = path;
|
|
|
|
m_context.recursive = recursive;
|
|
|
|
m_context.changes = appender!(DirectoryChange[]);
|
2018-03-16 17:06:53 +00:00
|
|
|
m_context.driver = () @trusted { return cast(shared)eventDriver; } ();
|
2016-10-25 06:57:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
this(this) nothrow { if (m_watcher != WatcherID.invalid) eventDriver.watchers.addRef(m_watcher); }
|
2018-03-16 17:06:53 +00:00
|
|
|
~this()
|
|
|
|
nothrow {
|
|
|
|
if (m_watcher != WatcherID.invalid)
|
|
|
|
releaseHandle!"watchers"(m_watcher, m_context.driver);
|
|
|
|
}
|
2016-10-25 06:57:16 +00:00
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
/// The path of the watched directory
|
2017-06-19 22:37:56 +00:00
|
|
|
@property NativePath path() const nothrow { return m_context.path; }
|
2016-03-01 19:30:42 +00:00
|
|
|
|
|
|
|
/// Indicates if the directory is watched recursively
|
2016-10-25 06:57:16 +00:00
|
|
|
@property bool recursive() const nothrow { return m_context.recursive; }
|
2016-03-01 19:30:42 +00:00
|
|
|
|
|
|
|
/** Fills the destination array with all changes that occurred since the last call.
|
|
|
|
|
|
|
|
The function will block until either directory changes have occurred or until the
|
|
|
|
timeout has elapsed. Specifying a negative duration will cause the function to
|
|
|
|
wait without a timeout.
|
|
|
|
|
|
|
|
Params:
|
|
|
|
dst = The destination array to which the changes will be appended
|
2016-10-25 06:57:16 +00:00
|
|
|
timeout = Optional timeout for the read operation. A value of
|
|
|
|
`Duration.max` will wait indefinitely.
|
2016-03-01 19:30:42 +00:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
If the call completed successfully, true is returned.
|
|
|
|
*/
|
2016-10-25 06:57:16 +00:00
|
|
|
bool readChanges(ref DirectoryChange[] dst, Duration timeout = Duration.max)
|
|
|
|
{
|
2017-01-29 21:11:17 +00:00
|
|
|
if (timeout == Duration.max) {
|
|
|
|
while (!m_context.changes.data.length)
|
|
|
|
m_context.changeEvent.wait(Duration.max, m_context.changeEvent.emitCount);
|
|
|
|
} else {
|
2018-12-23 21:22:53 +00:00
|
|
|
MonoTime now = MonoTime.currTime();
|
|
|
|
MonoTime final_time = now + timeout;
|
2017-01-29 21:11:17 +00:00
|
|
|
while (!m_context.changes.data.length) {
|
|
|
|
m_context.changeEvent.wait(final_time - now, m_context.changeEvent.emitCount);
|
2018-12-23 21:22:53 +00:00
|
|
|
now = MonoTime.currTime();
|
2017-01-29 21:11:17 +00:00
|
|
|
if (now >= final_time) break;
|
|
|
|
}
|
|
|
|
if (!m_context.changes.data.length) return false;
|
2016-10-25 06:57:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
dst = m_context.changes.data;
|
|
|
|
m_context.changes = appender!(DirectoryChange[]);
|
|
|
|
return true;
|
|
|
|
}
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** Specifies the kind of change in a watched directory.
|
|
|
|
*/
|
|
|
|
enum DirectoryChangeType {
|
|
|
|
/// A file or directory was added
|
|
|
|
added,
|
|
|
|
/// A file or directory was deleted
|
|
|
|
removed,
|
|
|
|
/// A file or directory was modified
|
|
|
|
modified
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** Describes a single change in a watched directory.
|
|
|
|
*/
|
|
|
|
struct DirectoryChange {
|
|
|
|
/// The type of change
|
|
|
|
DirectoryChangeType type;
|
|
|
|
|
|
|
|
/// Path of the file/directory that was changed
|
2017-06-19 22:37:56 +00:00
|
|
|
NativePath path;
|
2016-03-01 19:30:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private FileInfo makeFileInfo(DirEntry ent)
|
2019-03-24 20:36:50 +00:00
|
|
|
@trusted nothrow {
|
|
|
|
import std.algorithm.comparison : among;
|
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
FileInfo ret;
|
2019-04-04 14:20:46 +00:00
|
|
|
string fullname = ent.name;
|
2021-01-12 09:06:16 +00:00
|
|
|
if (fullname.length) {
|
2019-04-04 14:20:46 +00:00
|
|
|
if (ent.name[$-1].among('/', '\\'))
|
|
|
|
fullname = ent.name[0 .. $-1];
|
|
|
|
ret.name = baseName(fullname);
|
2021-01-12 09:06:16 +00:00
|
|
|
ret.directory = NativePath.fromTrustedString(dirName(fullname));
|
2019-04-04 14:20:46 +00:00
|
|
|
}
|
2019-03-24 20:36:50 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
ret.isFile = ent.isFile;
|
|
|
|
ret.isDirectory = ent.isDir;
|
|
|
|
ret.isSymlink = ent.isSymlink;
|
|
|
|
ret.timeModified = ent.timeLastModified;
|
|
|
|
version(Windows) ret.timeCreated = ent.timeCreated;
|
|
|
|
else ret.timeCreated = ent.timeLastModified;
|
|
|
|
ret.size = ent.size;
|
|
|
|
} catch (Exception e) {
|
|
|
|
logDebug("Failed to get information for file '%s': %s", fullname, e.msg);
|
|
|
|
}
|
|
|
|
|
2017-11-07 15:14:02 +00:00
|
|
|
version (Windows) {
|
|
|
|
import core.sys.windows.windows : FILE_ATTRIBUTE_HIDDEN;
|
|
|
|
ret.hidden = (ent.attributes & FILE_ATTRIBUTE_HIDDEN) != 0;
|
|
|
|
}
|
2019-04-04 14:20:46 +00:00
|
|
|
else ret.hidden = ret.name.length > 1 && ret.name[0] == '.' && ret.name != "..";
|
2019-03-24 20:36:50 +00:00
|
|
|
|
2016-03-01 19:30:42 +00:00
|
|
|
return ret;
|
|
|
|
}
|
2019-04-04 14:20:46 +00:00
|
|
|
|
|
|
|
version (Windows) {} else unittest {
|
|
|
|
void test(string name_in, string name_out, bool hidden) {
|
|
|
|
auto de = DirEntry(name_in);
|
|
|
|
assert(makeFileInfo(de).hidden == hidden);
|
|
|
|
assert(makeFileInfo(de).name == name_out);
|
|
|
|
}
|
|
|
|
|
|
|
|
void testCreate(string name_in, string name_out, bool hidden)
|
|
|
|
{
|
|
|
|
if (name_in.endsWith("/"))
|
|
|
|
createDirectory(name_in);
|
|
|
|
else writeFileUTF8(NativePath(name_in), name_in);
|
|
|
|
scope (exit) removeFile(name_in);
|
|
|
|
test(name_in, name_out, hidden);
|
|
|
|
}
|
|
|
|
|
|
|
|
test(".", ".", false);
|
|
|
|
test("..", "..", false);
|
|
|
|
testCreate(".test_foo", ".test_foo", true);
|
|
|
|
test("./", ".", false);
|
|
|
|
testCreate(".test_foo/", ".test_foo", true);
|
|
|
|
test("/", "", false);
|
|
|
|
}
|
2019-07-19 23:34:27 +00:00
|
|
|
|
|
|
|
unittest {
|
|
|
|
auto name = "toAppend.txt";
|
|
|
|
scope(exit) removeFile(name);
|
|
|
|
|
|
|
|
{
|
|
|
|
auto handle = openFile(name, FileMode.createTrunc);
|
|
|
|
handle.write("create,");
|
|
|
|
assert(handle.tell() == "create,".length);
|
|
|
|
handle.close();
|
|
|
|
}
|
|
|
|
{
|
|
|
|
auto handle = openFile(name, FileMode.append);
|
|
|
|
handle.write(" then append");
|
|
|
|
assert(handle.tell() == "create, then append".length);
|
|
|
|
handle.close();
|
|
|
|
}
|
|
|
|
|
|
|
|
assert(readFile(name) == "create, then append");
|
|
|
|
}
|
2019-08-25 10:02:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
private auto performInWorker(C, ARGS...)(C callable, auto ref ARGS args)
|
|
|
|
{
|
|
|
|
version (none) {
|
|
|
|
import vibe.core.concurrency : asyncWork;
|
|
|
|
return asyncWork(callable, args).getResult();
|
|
|
|
} else {
|
|
|
|
import vibe.core.core : runWorkerTask;
|
|
|
|
import core.atomic : atomicFence;
|
|
|
|
import std.concurrency : Tid, send, receiveOnly, thisTid;
|
|
|
|
|
|
|
|
struct R {}
|
|
|
|
|
|
|
|
alias RET = typeof(callable(args));
|
|
|
|
shared(RET) ret;
|
2020-03-18 14:32:26 +00:00
|
|
|
runWorkerTask(ioTaskSettings, (shared(RET)* r, Tid caller, C c, ref ARGS a) nothrow {
|
2019-08-25 10:02:08 +00:00
|
|
|
*() @trusted { return cast(RET*)r; } () = c(a);
|
|
|
|
// Just as a precaution, because ManualEvent is not well defined in
|
|
|
|
// terms of fence semantics
|
|
|
|
atomicFence();
|
|
|
|
try caller.send(R.init);
|
|
|
|
catch (Exception e) assert(false, e.msg);
|
|
|
|
}, () @trusted { return &ret; } (), thisTid, callable, args);
|
|
|
|
() @trusted { receiveOnly!R(); } ();
|
|
|
|
atomicFence();
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
}
|
2020-03-18 14:32:26 +00:00
|
|
|
|
2021-01-12 09:06:16 +00:00
|
|
|
private void performListDirectory(ListDirectoryRequest req)
|
|
|
|
@trusted nothrow {
|
|
|
|
scope (exit) req.channel.close();
|
|
|
|
|
2021-01-12 16:24:28 +00:00
|
|
|
auto dirs_only = !!(req.spanMode & DirectoryListMode.shallowDirectories);
|
|
|
|
auto rec = !!(req.spanMode & DirectoryListMode.recursive);
|
2021-01-12 09:06:16 +00:00
|
|
|
|
|
|
|
bool scanRec(NativePath path)
|
|
|
|
{
|
|
|
|
import std.algorithm.comparison : among;
|
|
|
|
import std.algorithm.searching : countUntil;
|
|
|
|
|
|
|
|
version (Windows) {
|
|
|
|
import core.sys.windows.windows : FILE_ATTRIBUTE_DIRECTORY,
|
|
|
|
FILE_ATTRIBUTE_DEVICE, FILE_ATTRIBUTE_HIDDEN,
|
|
|
|
FILE_ATTRIBUTE_REPARSE_POINT, FINDEX_INFO_LEVELS, FINDEX_SEARCH_OPS,
|
|
|
|
INVALID_HANDLE_VALUE, WIN32_FIND_DATAW,
|
|
|
|
FindFirstFileExW, FindNextFileW, FindClose;
|
|
|
|
import std.conv : to;
|
|
|
|
import std.utf : toUTF16z;
|
|
|
|
import std.windows.syserror : wenforce;
|
|
|
|
|
|
|
|
static immutable timebase = SysTime(DateTime(1601, 1, 1), UTC());
|
|
|
|
|
|
|
|
WIN32_FIND_DATAW fd;
|
|
|
|
FINDEX_INFO_LEVELS lvl;
|
|
|
|
static if (is(typeof(FINDEX_INFO_LEVELS.FindExInfoBasic)))
|
|
|
|
lvl = FINDEX_INFO_LEVELS.FindExInfoBasic;
|
|
|
|
else lvl = cast(FINDEX_INFO_LEVELS)1;
|
|
|
|
auto fh = FindFirstFileExW((path.toString ~ "\\*").toUTF16z,
|
|
|
|
lvl, &fd, dirs_only ? FINDEX_SEARCH_OPS.FindExSearchLimitToDirectories
|
|
|
|
: FINDEX_SEARCH_OPS.FindExSearchNameMatch,
|
|
|
|
null, 2/*FIND_FIRST_EX_LARGE_FETCH*/);
|
|
|
|
wenforce(fh != INVALID_HANDLE_VALUE, path.toString);
|
|
|
|
scope (exit) FindClose(fh);
|
|
|
|
do {
|
|
|
|
// skip non-directories if requested
|
|
|
|
if (dirs_only && !(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
FileInfo fi;
|
|
|
|
auto zi = fd.cFileName[].representation.countUntil(0);
|
|
|
|
if (zi < 0) zi = fd.cFileName.length;
|
|
|
|
if (fd.cFileName[0 .. zi].among("."w, ".."w))
|
|
|
|
continue;
|
|
|
|
fi.name = fd.cFileName[0 .. zi].to!string;
|
|
|
|
fi.directory = path;
|
|
|
|
fi.size = (ulong(fd.nFileSizeHigh) << 32) + fd.nFileSizeLow;
|
|
|
|
fi.timeModified = timebase + hnsecs((ulong(fd.ftLastWriteTime.dwHighDateTime) << 32) + fd.ftLastWriteTime.dwLowDateTime);
|
|
|
|
fi.timeCreated = timebase + hnsecs((ulong(fd.ftCreationTime.dwHighDateTime) << 32) + fd.ftCreationTime.dwLowDateTime);
|
|
|
|
fi.isSymlink = !!(fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT);
|
|
|
|
fi.isDirectory = !!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
|
|
|
|
fi.isFile = !fi.isDirectory && !(fd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE);
|
|
|
|
fi.hidden = !!(fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
|
|
|
|
|
|
|
|
try req.channel.put(ListDirectoryData(fi, null));
|
|
|
|
catch (Exception e) return false; // channel got closed
|
|
|
|
|
2021-01-12 16:24:28 +00:00
|
|
|
if (rec && fi.isDirectory) {
|
2021-01-12 09:06:16 +00:00
|
|
|
if (fi.isSymlink && !req.followSymlinks)
|
|
|
|
continue;
|
|
|
|
try {
|
|
|
|
if (!scanRec(path ~ NativePath.Segment2(fi.name)))
|
|
|
|
return false;
|
|
|
|
} catch (Exception e) {}
|
|
|
|
}
|
|
|
|
} while (FindNextFileW(fh, &fd));
|
|
|
|
} else {
|
|
|
|
import core.sys.posix.dirent : DT_DIR, DT_LNK, DT_UNKNOWN,
|
|
|
|
dirent, opendir, closedir, readdir;
|
|
|
|
import std.string : toStringz;
|
|
|
|
|
|
|
|
static immutable timebase = SysTime(DateTime(1970, 1, 1), UTC());
|
|
|
|
|
|
|
|
auto dir = opendir(path.toString.toStringz);
|
|
|
|
errnoEnforce(dir !is null, path.toString);
|
|
|
|
scope (exit) closedir(dir);
|
|
|
|
|
|
|
|
auto dfd = dirfd(dir);
|
|
|
|
|
|
|
|
dirent* de;
|
|
|
|
while ((de = readdir(dir)) !is null) {
|
|
|
|
// skip non-directories early, if possible
|
|
|
|
if (dirs_only && !de.d_type.among(DT_DIR, DT_LNK, DT_UNKNOWN))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
FileInfo fi;
|
2021-01-12 16:38:32 +00:00
|
|
|
auto zi = de.d_name[].representation.countUntil(0);
|
2021-01-12 09:06:16 +00:00
|
|
|
if (zi < 0) zi = de.d_name.length;
|
|
|
|
if (de.d_name[0 .. zi].among(".", ".."))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
fi.name = de.d_name[0 .. zi].idup;
|
|
|
|
fi.directory = path;
|
2021-01-12 16:24:28 +00:00
|
|
|
fi.hidden = de.d_name[0] == '.';
|
2021-01-12 09:06:16 +00:00
|
|
|
|
2021-01-18 09:42:21 +00:00
|
|
|
static SysTime getTimeField(string f)(ref const stat_t st)
|
|
|
|
{
|
|
|
|
long secs, nsecs;
|
|
|
|
static if (is(typeof(__traits(getMember, st, f)))) {
|
|
|
|
secs = __traits(getMember, st, f).tv_sec;
|
|
|
|
nsecs = __traits(getMember, st, f).tv_nsec;
|
|
|
|
} else {
|
|
|
|
secs = __traits(getMember, st, f ~ "e");
|
|
|
|
static if (is(typeof(__traits(getMember, st, f ~ "ensec"))))
|
|
|
|
nsecs = __traits(getMember, st, f ~ "ensec");
|
|
|
|
else static if (is(typeof(__traits(getMember, st, "__" ~ f ~ "ensec"))))
|
|
|
|
nsecs = __traits(getMember, st, "__" ~ f ~ "ensec");
|
|
|
|
else static if (is(typeof(__traits(getMember, st, "__" ~ f ~ "e_nsec"))))
|
|
|
|
nsecs = __traits(getMember, st, "__" ~ f ~ "e_nsec");
|
|
|
|
else static assert(false, "Found no nanoseconds fields in struct stat");
|
|
|
|
}
|
|
|
|
return timebase + secs.seconds + (nsecs / 100).hnsecs;
|
|
|
|
}
|
|
|
|
|
2021-01-12 09:06:16 +00:00
|
|
|
stat_t st;
|
2021-01-12 16:24:28 +00:00
|
|
|
if (fstatat(dfd, fi.name.toStringz, &st, AT_SYMLINK_NOFOLLOW) == 0) {
|
|
|
|
fi.isSymlink = S_ISLNK(st.st_mode);
|
2021-01-12 09:06:16 +00:00
|
|
|
|
2021-01-12 16:24:28 +00:00
|
|
|
// apart from the symlink flag, get the rest of the information from the link target
|
|
|
|
if (fi.isSymlink) fstatat(dfd, fi.name.toStringz, &st, 0);
|
2021-01-12 09:06:16 +00:00
|
|
|
|
2021-01-12 16:24:28 +00:00
|
|
|
fi.size = st.st_size;
|
2021-01-18 09:42:21 +00:00
|
|
|
fi.timeModified = getTimeField!"st_mtim"(st);
|
|
|
|
fi.timeCreated = getTimeField!"st_ctim"(st);
|
2021-01-12 16:24:28 +00:00
|
|
|
fi.isDirectory = S_ISDIR(st.st_mode);
|
|
|
|
fi.isFile = S_ISREG(st.st_mode);
|
|
|
|
}
|
2021-01-12 09:06:16 +00:00
|
|
|
|
|
|
|
// skip non-directories if requested
|
|
|
|
if (dirs_only && !fi.isDirectory)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
try req.channel.put(ListDirectoryData(fi, null));
|
|
|
|
catch (Exception e) return false; // channel got closed
|
|
|
|
|
2021-01-12 16:24:28 +00:00
|
|
|
if (rec && fi.isDirectory) {
|
2021-01-12 09:06:16 +00:00
|
|
|
if (fi.isSymlink && !req.followSymlinks)
|
|
|
|
continue;
|
|
|
|
try {
|
|
|
|
if (!scanRec(path ~ NativePath.Segment2(fi.name)))
|
|
|
|
return false;
|
|
|
|
} catch (Exception e) {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
try scanRec(req.path);
|
|
|
|
catch (Exception e) {
|
|
|
|
logException(e, "goo");
|
|
|
|
try req.channel.put(ListDirectoryData(FileInfo.init, e.msg.length ? e.msg : "Failed to iterate directory"));
|
|
|
|
catch (Exception e2) {} // channel got closed
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
version (Posix) {
|
|
|
|
import core.sys.posix.dirent : DIR;
|
|
|
|
import core.sys.posix.sys.stat : stat;
|
|
|
|
extern(C) @safe nothrow @nogc {
|
|
|
|
static if (!is(typeof(dirfd)))
|
|
|
|
int dirfd(DIR*);
|
2021-01-12 16:23:07 +00:00
|
|
|
static if (!is(typeof(fstatat))) {
|
|
|
|
version (OSX) {
|
|
|
|
pragma(mangle, "fstatat$INODE64")
|
|
|
|
int fstatat(int dirfd, const(char)* pathname, stat_t *statbuf, int flags);
|
|
|
|
} else int fstatat(int dirfd, const(char)* pathname, stat_t *statbuf, int flags);
|
|
|
|
}
|
2021-01-12 09:06:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
version (darwin) {
|
|
|
|
static if (!is(typeof(AT_SYMLINK_NOFOLLOW)))
|
|
|
|
enum AT_SYMLINK_NOFOLLOW = 0x0020;
|
|
|
|
}
|
2021-01-18 12:45:12 +00:00
|
|
|
|
|
|
|
version (CRuntime_Musl) {
|
|
|
|
static if (!is(typeof(AT_SYMLINK_NOFOLLOW)))
|
|
|
|
enum AT_SYMLINK_NOFOLLOW = 0x0100;
|
|
|
|
}
|
2021-01-12 09:06:16 +00:00
|
|
|
}
|
|
|
|
|
2020-03-18 14:32:26 +00:00
|
|
|
private immutable TaskSettings ioTaskSettings = { priority: 20 * Task.basePriority };
|
2021-01-12 09:06:16 +00:00
|
|
|
|
|
|
|
private struct ListDirectoryData {
|
|
|
|
FileInfo info;
|
|
|
|
string error;
|
|
|
|
}
|
|
|
|
|
|
|
|
private struct ListDirectoryRequest {
|
|
|
|
import vibe.core.channel : Channel;
|
|
|
|
|
|
|
|
NativePath path;
|
|
|
|
DirectoryListMode spanMode;
|
|
|
|
Channel!ListDirectoryData channel;
|
|
|
|
bool followSymlinks;
|
|
|
|
}
|