abraunegg-onedrive/src/util.d

69 lines
1.2 KiB
D
Raw Normal View History

2015-09-21 13:04:05 +02:00
import std.conv, std.digest.crc, std.digest.digest, std.file, std.path;
import std.regex, std.stdio, std.string: chomp;
2015-09-01 20:45:34 +02:00
private string deviceName;
static this()
{
import std.socket;
deviceName = Socket.hostName;
}
// give a new name to the specified file or directory
void safeRename(const(char)[] path)
{
auto ext = extension(path);
auto newPath = path.chomp(ext) ~ "-" ~ deviceName;
if (exists(newPath ~ ext)) {
int n = 2;
char[] newPath2;
do {
newPath2 = newPath ~ "-" ~ n.to!string;
n++;
} while (exists(newPath2 ~ ext));
newPath = newPath2;
}
newPath ~= ext;
rename(path, newPath);
}
// return the crc32 hex string of a file
string computeCrc32(string path)
{
CRC32 crc;
auto file = File(path, "rb");
foreach (ubyte[] data; chunks(file, 4096)) {
crc.put(data);
}
return crc.finish().toHexString().dup;
}
2015-09-19 09:45:45 +02:00
// convert wildcards (*, ?) to regex
2015-09-21 13:04:05 +02:00
Regex!char wild2regex(const(char)[] pattern)
2015-09-19 09:45:45 +02:00
{
2015-09-21 13:04:05 +02:00
string str;
str.reserve(pattern.length + 2);
2015-09-22 11:16:06 +02:00
str ~= "/";
2015-09-19 09:45:45 +02:00
foreach (c; pattern) {
switch (c) {
case '*':
2015-09-21 13:04:05 +02:00
str ~= "[^/]*";
2015-09-19 09:45:45 +02:00
break;
case '.':
2015-09-21 13:04:05 +02:00
str ~= "\\.";
2015-09-19 09:45:45 +02:00
break;
case '?':
2015-09-21 13:04:05 +02:00
str ~= "[^/]";
2015-09-19 09:45:45 +02:00
break;
case '|':
2015-09-22 11:16:06 +02:00
str ~= "$|/";
2015-09-19 09:45:45 +02:00
break;
default:
2015-09-21 13:04:05 +02:00
str ~= c;
2015-09-19 09:45:45 +02:00
break;
}
}
2015-09-21 13:04:05 +02:00
str ~= "$";
return regex(str, "i");
2015-09-19 09:45:45 +02:00
}