This commit is contained in:
Timerix22 2022-12-05 22:08:48 +06:00
parent 4e5190b91d
commit 92997c9325
12 changed files with 54 additions and 240 deletions

View File

@ -27,7 +27,7 @@ public class FileLogger : ILogger
{}
public FileLogger(string dir, string programName, ILogFormat format)
: this($"{dir}{Путь.Разд}{programName}_{DateTime.Now.ToString(MyTimeFormat.ForFileNames)}.log", format)
: this($"{dir}{Path.Sep}{programName}_{DateTime.Now.ToString(MyTimeFormat.ForFileNames)}.log", format)
{}
public FileLogger(string dir, string programName) : this(dir, programName, new DefaultLogFormat())

View File

@ -18,8 +18,8 @@ public class FSP
// скачивает файл с помощью FSP протокола
public void DownloadFile(string filePath_server, string filePath_client)
{
Путь.Предупредить(filePath_server);
Путь.Предупредить(filePath_client);
Path.ThrowIfEscapes(filePath_server);
Path.ThrowIfEscapes(filePath_client);
lock (MainSocket)
{
Debug("b", $"requesting file download: {filePath_server}");
@ -31,7 +31,7 @@ public class FSP
public void DownloadFile(string filePath_client)
{
Путь.Предупредить(filePath_client);
Path.ThrowIfEscapes(filePath_client);
using System.IO.Stream fileStream = File.OpenWrite(filePath_client);
Download_SharedCode(fileStream, true);
fileStream.Close();
@ -40,7 +40,7 @@ public class FSP
public byte[] DownloadFileToMemory(string filePath_server)
{
Путь.Предупредить(filePath_server);
Path.ThrowIfEscapes(filePath_server);
lock (MainSocket)
{
Debug("b", $"requesting file download: {filePath_server}");
@ -102,7 +102,7 @@ public class FSP
// отдаёт файл с помощью FSP протокола
public void UploadFile(string filePath)
{
Путь.Предупредить(filePath);
Path.ThrowIfEscapes(filePath);
BytesUploaded = 0;
Debug("b", $"uploading file {filePath}");
using System.IO.FileStream fileStream = File.OpenRead(filePath);
@ -137,10 +137,10 @@ public class FSP
public void DownloadByManifest(string dirOnServer, string dirOnClient, bool overwrite = false, bool delete_excess = false)
{
if (!dirOnClient.EndsWith(Путь.Разд))
dirOnClient += Путь.Разд;
if (!dirOnServer.EndsWith(Путь.Разд))
dirOnServer += Путь.Разд;
if (!dirOnClient.EndsWith(Path.Sep))
dirOnClient += Path.Sep;
if (!dirOnServer.EndsWith(Path.Sep))
dirOnServer += Path.Sep;
Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">");
var manifest = new DtsodV23(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString(StringConverter.UTF8));
Debug("g", $"found {manifest.Values.Count} files in manifest");
@ -183,8 +183,8 @@ public class FSP
Log("y", $"can't create manifest, dir <{dir}> doesn't exist");
return;
}
if (!dir.EndsWith(Путь.Разд))
dir += Путь.Разд;
if (!dir.EndsWith(Path.Sep))
dir += Path.Sep;
Log($"b", $"creating manifest of {dir}");
StringBuilder manifestBuilder = new();
Hasher hasher = new();

View File

@ -17,7 +17,7 @@ public static class TestDtsodV23
public static void TestBaseTypes()
{
OldLogger.Log("c", "-----[TestDtsodV23/TestBaseTypes]-----");
DtsodV23 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}base_types.dtsod"));
DtsodV23 dtsod = new(File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV23{Path.Sep}base_types.dtsod"));
foreach (var pair in dtsod)
OldLogger.Log("b", pair.Value.GetType().Name + ' ', "w", pair.Key + ' ', "c", pair.Value.ToString());
OldLogger.Log("g", "test completed");
@ -25,7 +25,7 @@ public static class TestDtsodV23
public static void TestLists()
{
OldLogger.Log("c", "-------[TestDtsodV23/TestLists]-------");
DtsodV23 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}lists.dtsod"));
DtsodV23 dtsod = new(File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV23{Path.Sep}lists.dtsod"));
foreach (var pair in dtsod)
{
OldLogger.Log("b", pair.Value.GetType().Name + ' ', "w", pair.Key, "c",
@ -39,7 +39,7 @@ public static class TestDtsodV23
public static void TestComplexes()
{
OldLogger.Log("c", "-----[TestDtsodV23/TestComplexes]-----");
DtsodV23 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}complexes.dtsod"));
DtsodV23 dtsod = new(File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV23{Path.Sep}complexes.dtsod"));
foreach (var complex in dtsod)
{
OldLogger.Log("b", complex.Value.GetType().Name + ' ', "w", complex.Key,
@ -55,7 +55,7 @@ public static class TestDtsodV23
{
OldLogger.Log("c", "--[TestDtsodV23/TestReSerialization]--");
var dtsod = new DtsodV23(new DtsodV23(new DtsodV23(
new DtsodV23(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}complexes.dtsod")).ToString()).ToString()).ToString());
new DtsodV23(File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV23{Path.Sep}complexes.dtsod")).ToString()).ToString()).ToString());
OldLogger.Log("y", dtsod.ToString());
OldLogger.Log("g", "test completed");
}
@ -64,7 +64,7 @@ public static class TestDtsodV23
{
OldLogger.Log("c", "-------[TestDtsodV23/TestSpeed]-------");
IDtsod dtsod=null;
string text = File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}messages.dtsod");
string text = File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV23{Path.Sep}messages.dtsod");
LogOperationTime("V21 deserialization",64,()=>dtsod=new DtsodV21(text));
LogOperationTime("V21 serialization", 64, () => _=dtsod.ToString());
LogOperationTime("V23 deserialization", 64, () => dtsod = new DtsodV23(text));
@ -75,7 +75,7 @@ public static class TestDtsodV23
public static void TestMemoryConsumption()
{
OldLogger.Log("c", "----[TestDtsodV23/TestMemConsumpt]----");
string text = File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}messages.dtsod");
string text = File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV23{Path.Sep}messages.dtsod");
var a = GC.GetTotalMemory(true);
var dtsods = new DtsodV23[64];
for (int i = 0; i < dtsods.Length; i++)

View File

@ -18,7 +18,7 @@ public static class TestDtsodV24
public static void TestBaseTypes()
{
OldLogger.Log("c", "-----[TestDtsodV24/TestBaseTypes]-----");
DtsodV24 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}base_types.dtsod"));
DtsodV24 dtsod = new(File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV24{Path.Sep}base_types.dtsod"));
foreach (var pair in dtsod)
OldLogger.Log("b", pair.ToString());
OldLogger.Log("g", "test completed");
@ -27,7 +27,7 @@ public static class TestDtsodV24
public static void TestComplexes()
{
OldLogger.Log("c", "-----[TestDtsodV24/TestComplexes]-----");
DtsodV24 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}complexes.dtsod"));
DtsodV24 dtsod = new(File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV24{Path.Sep}complexes.dtsod"));
OldLogger.Log("h", dtsod.ToString());
OldLogger.Log("g", "test completed");
}
@ -35,7 +35,7 @@ public static class TestDtsodV24
public static void TestLists()
{
OldLogger.Log("c", "-------[TestDtsodV24/TestLists]-------");
DtsodV24 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}lists.dtsod"));
DtsodV24 dtsod = new(File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV24{Path.Sep}lists.dtsod"));
foreach (KVPair pair in dtsod)
{
var list = new Autoarr<Unitype>(pair.value.VoidPtr, false);
@ -60,7 +60,7 @@ public static class TestDtsodV24
{
OldLogger.Log("c", "--[TestDtsodV24/TestReSerialization]--");
var dtsod = new DtsodV24(new DtsodV24(new DtsodV24(
new DtsodV24(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}complexes.dtsod")).ToString()).ToString()).ToString());
new DtsodV24(File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV24{Path.Sep}complexes.dtsod")).ToString()).ToString()).ToString());
OldLogger.Log("h", dtsod.ToString());
OldLogger.Log("g", "test completed");
}
@ -69,12 +69,12 @@ public static class TestDtsodV24
{
OldLogger.Log("c", "-------[TestDtsodV24/TestSpeed]-------");
IDtsod dtsod=null;
string _text = File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}messages.dtsod");
string _text = File.ReadAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV23{Path.Sep}messages.dtsod");
string text = "";
LogOperationTime( "V23 to V24 conversion", 32, ()=>
text = DtsodConverter.ConvertVersion(new DtsodV23(_text), DtsodVersion.V24).ToString()
);
File.WriteAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}messages.dtsod",text);
File.WriteAllText($"Dtsod{Path.Sep}TestResources{Path.Sep}DtsodV24{Path.Sep}messages.dtsod",text);
LogOperationTime("V24 deserialization", 64, () => dtsod = new DtsodV24(text));
LogOperationTime("V24 serialization", 64, () => text = dtsod.ToString());
OldLogger.Log("g", "test completed");

View File

@ -9,14 +9,14 @@ public static class DependencyResolver
public static void CopyLibs()
{
if(DepsCopied) return;
string depsdir = $"Dependencies{Путь.Разд}";
string depsdir = $"Dependencies{Path.Sep}";
depsdir += Environment.OSVersion.Platform switch
{
PlatformID.Unix => "linux",
PlatformID.Win32NT => "windows",
_=> throw new Exception($"unsupported os {Environment.OSVersion.Platform}")
};
depsdir += Путь.Разд;
depsdir += Path.Sep;
depsdir += RuntimeInformation.ProcessArchitecture switch
{
Architecture.X64 => "x64",
@ -27,7 +27,7 @@ public static class DependencyResolver
};
foreach (var file in Directory.GetAllFiles(depsdir))
{
var extracted = file.Substring(file.LastIndexOf(Путь.Разд) + 1);
var extracted = file.Substring(file.LastIndexOf(Path.Sep) + 1);
File.Copy(file,extracted, true);
Log("g",$"{extracted} copied");
}

View File

@ -1,8 +1,8 @@
using System.IO;
namespace DTLib.Filesystem.New;
namespace DTLib.Experimental;
public class File
public class FileInstance
{
public enum FileOpenMode
{
@ -22,9 +22,11 @@ public class File
public readonly FileStream Stream;
public string Name;
public File(string path, FileOpenMode mode)
public FileInstance(string path, FileOpenMode mode)
{
if(!Exists(path))
if (path.IsNullOrEmpty())
throw new NullReferenceException("path is null");
if(!System.IO.File.Exists(path))
{
if (mode == FileOpenMode.Read)
throw new Exception($"file <{path}> is not found");
@ -40,25 +42,4 @@ public class File
_ => throw new Exception($"unknown file mode: {mode}")
};
}
public static bool Exists(string path) => System.IO.File.Exists(path);
public static void Create(string path)
{
if (Exists(path))
throw new Exception($"file <{path} already exists");
int sepIndex = path.LastIndexOf(Path.Sep);
if (sepIndex>-1)
Directory.Create(path.Remove(sepIndex));
System.IO.File.Create(path).Close();
}
public static void Delete(string path) => System.IO.File.Delete(path);
public static void Copy(string srcPath, string newPath, bool replace = false)
{
System.IO.File.Copy(srcPath, newPath, replace);
}
// public void Delete(string path)
}

View File

@ -10,8 +10,8 @@ public static class Directory
if (!Exists(dir))
{
// проверяет существование папки, в которой нужно создать dir
if (dir.Contains(Путь.Разд) && !Exists(dir.Remove(dir.LastIndexOf(Путь.Разд))))
Create(dir.Remove(dir.LastIndexOf(Путь.Разд)));
if (dir.Contains(Path.Sep) && !Exists(dir.Remove(dir.LastIndexOf(Path.Sep))))
Create(dir.Remove(dir.LastIndexOf(Path.Sep)));
System.IO.Directory.CreateDirectory(dir);
}
}
@ -100,8 +100,8 @@ public static class Directory
public static void CreateSymlink(string sourceName, string symlinkName)
{
if (symlinkName.Contains(Путь.Разд))
Create(symlinkName.Remove(symlinkName.LastIndexOf(Путь.Разд)));
if (symlinkName.Contains(Path.Sep))
Create(symlinkName.Remove(symlinkName.LastIndexOf(Path.Sep)));
if (!Symlink.CreateSymbolicLink(symlinkName, sourceName, Symlink.SymlinkTarget.Directory))
throw new InvalidOperationException($"some error occured while creating symlink\nDirectory.CreateSymlink({symlinkName}, {sourceName})");
}
@ -110,8 +110,8 @@ public static class Directory
public static int SymCopy(string srcdir, string newdir)
{
List<string> files = GetAllFiles(srcdir);
if (!srcdir.EndsWith(Путь.Разд)) srcdir += Путь.Разд;
if (!newdir.EndsWith(Путь.Разд)) newdir += Путь.Разд;
if (!srcdir.EndsWith(Path.Sep)) srcdir += Path.Sep;
if (!newdir.EndsWith(Path.Sep)) newdir += Path.Sep;
int i = 0;
for (; i < files.Count; i++)
File.CreateSymlink(files[i], files[i].Replace(srcdir, newdir));

View File

@ -12,8 +12,8 @@ public static class File
{
if (!Exists(file))
{
if (file.Contains(Путь.Разд))
Directory.Create(file.Remove(file.LastIndexOf(Путь.Разд)));
if (file.Contains(Path.Sep))
Directory.Create(file.Remove(file.LastIndexOf(Path.Sep)));
using System.IO.FileStream stream = System.IO.File.Create(file);
stream.Close();
}
@ -79,8 +79,8 @@ public static class File
public static void CreateSymlink(string sourceName, string symlinkName)
{
if (symlinkName.Contains(Путь.Разд))
Directory.Create(symlinkName.Remove(symlinkName.LastIndexOf(Путь.Разд)));
if (symlinkName.Contains(Path.Sep))
Directory.Create(symlinkName.Remove(symlinkName.LastIndexOf(Path.Sep)));
if (!Symlink.CreateSymbolicLink(symlinkName, sourceName, Symlink.SymlinkTarget.File))
throw new InvalidOperationException($"some error occured while creating symlink\nFile.CreateSymlink({symlinkName}, {sourceName})");
}

View File

@ -1,120 +0,0 @@
namespace DTLib.Filesystem.New;
public static class Directory
{
public static bool Exists(string dir) => System.IO.Directory.Exists(dir);
// создает папку, если её не существует
public static void Create(string dir)
{
if (!Exists(dir))
{
// проверяет существование папки, в которой нужно создать dir
if (dir.Contains(Путь.Разд) && !Exists(dir.Remove(dir.LastIndexOf(Путь.Разд))))
Create(dir.Remove(dir.LastIndexOf(Путь.Разд)));
System.IO.Directory.CreateDirectory(dir);
}
}
// копирует все файлы и папки
public static void Copy(string source_dir, string new_dir, bool owerwrite = false)
{
Create(new_dir);
var subdirs = new List<string>();
List<string> files = GetAllFiles(source_dir, ref subdirs);
for (int i = 0; i < subdirs.Count; i++)
Create(subdirs[i].Replace(source_dir, new_dir));
for (int i = 0; i < files.Count; i++)
File.Copy(files[i], files[i].Replace(source_dir, new_dir), owerwrite);
}
// копирует все файлы и папки и выдаёт список конфликтующих файлов
public static void Copy(string source_dir, string new_dir, out List<string> conflicts, bool owerwrite = false)
{
conflicts = new List<string>();
var subdirs = new List<string>();
List<string> files = GetAllFiles(source_dir, ref subdirs);
Create(new_dir);
for (int i = 0; i < subdirs.Count; i++)
Create(subdirs[i].Replace(source_dir, new_dir));
for (int i = 0; i < files.Count; i++)
{
string newfile = files[i].Replace(source_dir, new_dir);
if (File.Exists(newfile))
conflicts.Add(newfile);
File.Copy(files[i], newfile, owerwrite);
}
}
// удаляет папку со всеми подпапками и файлами
public static void Delete(string dir)
{
var subdirs = new List<string>();
List<string> files = GetAllFiles(dir, ref subdirs);
for (int i = 0; i < files.Count; i++)
File.Delete(files[i]);
for (int i = subdirs.Count - 1; i >= 0; i--)
{
Log($"deleting {subdirs[i]}");
if (Exists(subdirs[i]))
System.IO.Directory.Delete(subdirs[i], true);
}
Log($"deleting {dir}");
if (Exists(dir))
System.IO.Directory.Delete(dir, true);
}
public static string[] GetFiles(string dir) => System.IO.Directory.GetFiles(dir);
public static string[] GetFiles(string dir, string searchPattern) => System.IO.Directory.GetFiles(dir, searchPattern);
public static string[] GetDirectories(string dir) => System.IO.Directory.GetDirectories(dir);
// выдает список всех файлов
public static List<string> GetAllFiles(string dir)
{
var all_files = new List<string>();
string[] cur_files = GetFiles(dir);
for (int i = 0; i < cur_files.Length; i++)
all_files.Add(cur_files[i]);
string[] cur_subdirs = GetDirectories(dir);
for (int i = 0; i < cur_subdirs.Length; i++)
all_files.AddRange(GetAllFiles(cur_subdirs[i]));
return all_files;
}
// выдает список всех файлов и подпапок в папке
public static List<string> GetAllFiles(string dir, ref List<string> all_subdirs)
{
var all_files = new List<string>();
string[] cur_files = GetFiles(dir);
for (int i = 0; i < cur_files.Length; i++)
all_files.Add(cur_files[i]);
string[] cur_subdirs = GetDirectories(dir);
for (int i = 0; i < cur_subdirs.Length; i++)
{
all_subdirs.Add(cur_subdirs[i]);
all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs));
}
return all_files;
}
public static string GetCurrent() => System.IO.Directory.GetCurrentDirectory();
public static void CreateSymlink(string sourceName, string symlinkName)
{
if (symlinkName.Contains(Путь.Разд))
Create(symlinkName.Remove(symlinkName.LastIndexOf(Путь.Разд)));
if (!Symlink.CreateSymbolicLink(symlinkName, sourceName, Symlink.SymlinkTarget.Directory))
throw new InvalidOperationException($"some error occured while creating symlink\nDirectory.CreateSymlink({symlinkName}, {sourceName})");
}
// copies directory with symlinks instead of files
/*public static int SymCopy(string srcdir, string newdir)
{
List<string> files = GetAllFiles(srcdir);
if (!srcdir.EndsWith(Путь.Разд)) srcdir += Путь.Разд;
if (!newdir.EndsWith(Путь.Разд)) newdir += Путь.Разд;
int i = 0;
for (; i < files.Count; i++)
File.CreateSymlink(files[i], files[i].Replace(srcdir, newdir));
return i;
}*/
}

View File

@ -1,6 +1,6 @@
using System.Runtime.CompilerServices;
namespace DTLib.Filesystem.New;
namespace DTLib.Filesystem;
public static class Path
{
@ -50,33 +50,17 @@ public static class Path
{
switch (a[i])
{
case '/':
case '\\':
case ':':
case ';':
case '/': case '\\':
case ':': case ';':
r[i] = '-';
break;
case '\n':
case '\r':
case ' ':
case '#':
case '%':
case '&':
case '{':
case '}':
case '<':
case '>':
case '*':
case '?':
case '$':
case '!':
case '\'':
case '"':
case '@':
case '+':
case '`':
case '|':
case '=':
case '\n': case '\r': case ' ':
case '#': case '%': case '&':
case '{': case '}': case '<':
case '>': case '*': case '?':
case '$': case '!': case '\'':
case '"': case '@': case '+':
case '`': case '|': case '=':
r[i] = '_';
break;
default:

View File

@ -1,31 +0,0 @@
namespace DTLib.Filesystem;
public static class Путь
{
public static readonly char Разд = Environment.OSVersion.Platform == PlatformID.Win32NT ? '\\' : '/';
public static string ИсправитьРазд(this string путь)
{
if (Разд == '\\')
{
if (путь.Contains('/'))
путь = путь.Replace('/', '\\');
}
else
{
if (путь.Contains('\\'))
путь = путь.Replace('\\', '/');
}
return путь;
}
// replaces wrong characters to use string as путь
public static string НормализоватьДляПути(this string путь) =>
путь.Replace(':', '-').Replace(' ', '_');
public static void Предупредить(string может_быть_сочками)
{
if(может_быть_сочками.Contains(".."))
throw new Exception($"лее точки двойные убери: {может_быть_сочками}");
}
}

View File

@ -9,7 +9,7 @@ public class FileLogger : IDisposable
}
public FileLogger(string dir, string programName)
: this($"{dir}{Путь.Разд}{programName}_{DateTime.Now.ToString(MyTimeFormat.ForFileNames)}.log") { }
: this($"{dir}{Path.Sep}{programName}_{DateTime.Now.ToString(MyTimeFormat.ForFileNames)}.log") { }
public string LogfileName { get; protected set; }
public System.IO.FileStream LogfileStream { get; protected set; }