small changes

This commit is contained in:
Timerix22 2022-01-14 00:04:06 +03:00
parent 54d9a43e75
commit 97269fd160
11 changed files with 55 additions and 69 deletions

View File

@ -75,7 +75,7 @@ dotnet_style_allow_statement_immediately_after_block_experimental = true
#### Рекомендации по написанию кода C# #### #### Рекомендации по написанию кода C# ####
# Предпочтения var # Предпочтения var
csharp_style_var_elsewhere = false csharp_style_var_elsewhere = true
csharp_style_var_for_built_in_types = false csharp_style_var_for_built_in_types = false
csharp_style_var_when_type_is_apparent = true csharp_style_var_when_type_is_apparent = true

View File

@ -7,10 +7,14 @@
<AssemblyName>DTLib</AssemblyName> <AssemblyName>DTLib</AssemblyName>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ProduceReferenceAssembly>False</ProduceReferenceAssembly>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Remove="Experimental\**" /> <Compile Remove="Experimental\**" />
<EmbeddedResource Remove="Experimental\**" /> <EmbeddedResource Remove="Experimental\**" />
<None Remove="Experimental\**" /> <None Remove="Experimental\**" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Compile Include="Experimental\Tester.cs" />
</ItemGroup>
</Project> </Project>

View File

@ -1,10 +1,9 @@
using System; using System.Diagnostics;
using System.Diagnostics;
namespace DTLib.Experimental namespace DTLib.Experimental;
public static class Tester
{ {
public static class Tester
{
public static void LogOperationTime(string op_name, int repeats, Action operation) public static void LogOperationTime(string op_name, int repeats, Action operation)
{ {
Stopwatch clock = new(); Stopwatch clock = new();
@ -12,7 +11,6 @@ namespace DTLib.Experimental
for (int i = 0; i < repeats; i++) for (int i = 0; i < repeats; i++)
operation(); operation();
clock.Stop(); clock.Stop();
PublicLog.LogNoTime("c",$"operation {op_name} took {clock.ElapsedTicks / repeats} ticks\n"); LogNoTime("c",$"operation {op_name} took {clock.ElapsedTicks / repeats} ticks");
}
} }
} }

View File

@ -1,6 +1,7 @@
global using System; global using System;
global using System.Collections; global using System.Collections;
global using System.Collections.Generic; global using System.Collections.Generic;
global using System.Linq;
global using System.Text; global using System.Text;
global using System.Threading.Tasks; global using System.Threading.Tasks;
global using DTLib.Extensions; global using DTLib.Extensions;

View File

@ -144,10 +144,4 @@ public static class StringConverter
if (max * length != s.Length) parts.Add(s.Substring(max * length, s.Length - max * length)); if (max * length != s.Length) parts.Add(s.Substring(max * length, s.Length - max * length));
return parts; return parts;
} }
public static string AddZeroes<T>(this T number, int length)
{
string str = number.ToString();
return new string('0', str.Length - length) + str;
}
} }

View File

@ -10,7 +10,7 @@ public static class Directory
if (!Directory.Exists(dir)) if (!Directory.Exists(dir))
{ {
// проверяет существование папки, в которой нужно создать dir // проверяет существование папки, в которой нужно создать dir
if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\')))) if (dir.Contains('\\') && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
Create(dir.Remove(dir.LastIndexOf('\\'))); Create(dir.Remove(dir.LastIndexOf('\\')));
System.IO.Directory.CreateDirectory(dir); System.IO.Directory.CreateDirectory(dir);
} }
@ -22,15 +22,9 @@ public static class Directory
var subdirs = new List<string>(); var subdirs = new List<string>();
List<string> files = GetAllFiles(source_dir, ref subdirs); List<string> files = GetAllFiles(source_dir, ref subdirs);
for (int i = 0; i < subdirs.Count; i++) for (int i = 0; i < subdirs.Count; i++)
{
Create(subdirs[i].Replace(source_dir, new_dir)); Create(subdirs[i].Replace(source_dir, new_dir));
}
for (int i = 0; i < files.Count; i++) for (int i = 0; i < files.Count; i++)
{ File.Copy(files[i], files[i].Replace(source_dir, new_dir), owerwrite);
string f = files[i].Replace(source_dir, new_dir);
File.Copy(files[i], f, owerwrite);
//PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
}
} }
// копирует все файлы и папки и выдаёт список конфликтующих файлов // копирует все файлы и папки и выдаёт список конфликтующих файлов
@ -41,16 +35,13 @@ public static class Directory
List<string> files = GetAllFiles(source_dir, ref subdirs); List<string> files = GetAllFiles(source_dir, ref subdirs);
Create(new_dir); Create(new_dir);
for (int i = 0; i < subdirs.Count; i++) for (int i = 0; i < subdirs.Count; i++)
{
Create(subdirs[i].Replace(source_dir, new_dir)); Create(subdirs[i].Replace(source_dir, new_dir));
}
for (int i = 0; i < files.Count; i++) for (int i = 0; i < files.Count; i++)
{ {
string newfile = files[i].Replace(source_dir, new_dir); string newfile = files[i].Replace(source_dir, new_dir);
if (File.Exists(newfile)) if (File.Exists(newfile))
conflicts.Add(newfile); conflicts.Add(newfile);
File.Copy(files[i], newfile, owerwrite); File.Copy(files[i], newfile, owerwrite);
//PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
} }
} }
@ -63,11 +54,11 @@ public static class Directory
File.Delete(files[i]); File.Delete(files[i]);
for (int i = subdirs.Count - 1; i >= 0; i--) for (int i = subdirs.Count - 1; i >= 0; i--)
{ {
PublicLog.Log($"deleting {subdirs[i]}\n"); PublicLog.Log($"deleting {subdirs[i]}");
if (Directory.Exists(subdirs[i])) if (Directory.Exists(subdirs[i]))
System.IO.Directory.Delete(subdirs[i], true); System.IO.Directory.Delete(subdirs[i], true);
} }
PublicLog.Log($"deleting {dir}\n"); PublicLog.Log($"deleting {dir}");
if (Directory.Exists(dir)) if (Directory.Exists(dir))
System.IO.Directory.Delete(dir, true); System.IO.Directory.Delete(dir, true);
} }
@ -82,16 +73,10 @@ public static class Directory
var all_files = new List<string>(); var all_files = new List<string>();
string[] cur_files = Directory.GetFiles(dir); string[] cur_files = Directory.GetFiles(dir);
for (int i = 0; i < cur_files.Length; i++) for (int i = 0; i < cur_files.Length; i++)
{
all_files.Add(cur_files[i]); all_files.Add(cur_files[i]);
//PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
}
string[] cur_subdirs = Directory.GetDirectories(dir); string[] cur_subdirs = Directory.GetDirectories(dir);
for (int i = 0; i < cur_subdirs.Length; i++) for (int i = 0; i < cur_subdirs.Length; i++)
{
//PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
all_files.AddRange(GetAllFiles(cur_subdirs[i])); all_files.AddRange(GetAllFiles(cur_subdirs[i]));
}
return all_files; return all_files;
} }
@ -101,15 +86,11 @@ public static class Directory
var all_files = new List<string>(); var all_files = new List<string>();
string[] cur_files = Directory.GetFiles(dir); string[] cur_files = Directory.GetFiles(dir);
for (int i = 0; i < cur_files.Length; i++) for (int i = 0; i < cur_files.Length; i++)
{
all_files.Add(cur_files[i]); all_files.Add(cur_files[i]);
//PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
}
string[] cur_subdirs = Directory.GetDirectories(dir); string[] cur_subdirs = Directory.GetDirectories(dir);
for (int i = 0; i < cur_subdirs.Length; i++) for (int i = 0; i < cur_subdirs.Length; i++)
{ {
all_subdirs.Add(cur_subdirs[i]); all_subdirs.Add(cur_subdirs[i]);
//PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs)); all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs));
} }
return all_files; return all_files;

View File

@ -50,7 +50,7 @@ public class Hasher
//var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second; //var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
byte[] hash = xxh32.ComputeHash(fileStream); byte[] hash = xxh32.ComputeHash(fileStream);
//var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second; //var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
//PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}\n"); //PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}");
fileStream.Close(); fileStream.Close();
return hash; return hash;
} }

View File

@ -3,11 +3,14 @@
public abstract class BaseLogger public abstract class BaseLogger
{ {
public string Logfile { get; init; } public string Logfile { get; init; }
public BaseLogger(string logfile) => Logfile = logfile; public BaseLogger() { }
public BaseLogger(string dir, string programName) => Logfile = $"{dir}\\{programName}_{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_'); public BaseLogger(string logfile) => (Logfile, WriteToFile) = (logfile,true);
public BaseLogger(string dir, string programName)
: this($"{dir}\\{programName}_{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_')) { }
public bool IsEnabled { get; private set; } = false; public bool IsEnabled { get; private set; } = false;
public bool WriteToFile { get; private set; } = false;
protected readonly object statelocker = new(); protected readonly object statelocker = new();
public void Disable() { lock (statelocker) IsEnabled = false; } public void Disable() { lock (statelocker) IsEnabled = false; }
public void Enable() { lock (statelocker) IsEnabled = true; } public void Enable() { lock (statelocker) IsEnabled = true; }

View File

@ -3,6 +3,7 @@
// вывод лога в консоль и файл // вывод лога в консоль и файл
public class DefaultLogger : BaseLogger public class DefaultLogger : BaseLogger
{ {
public DefaultLogger() => Logfile = "";
public DefaultLogger(string logfile) : base(logfile) { } public DefaultLogger(string logfile) : base(logfile) { }
public DefaultLogger(string dir, string programName) : base(dir, programName) { } public DefaultLogger(string dir, string programName) : base(dir, programName) { }
@ -18,7 +19,10 @@ public class DefaultLogger : BaseLogger
public void LogNoTime(params string[] msg) public void LogNoTime(params string[] msg)
{ {
lock (Logfile) if (!IsEnabled) return; lock (Logfile) if (!IsEnabled) return;
msg[msg.Length - 1] += '\n';
ColoredConsole.Write(msg); ColoredConsole.Write(msg);
if (WriteToFile)
{
if (msg.Length == 1) if (msg.Length == 1)
lock (Logfile) File.AppendAllText(Logfile, msg[0]); lock (Logfile) File.AppendAllText(Logfile, msg[0]);
else else
@ -29,4 +33,5 @@ public class DefaultLogger : BaseLogger
lock (Logfile) File.AppendAllText(Logfile, strB.ToString()); lock (Logfile) File.AppendAllText(Logfile, strB.ToString());
} }
} }
}
} }

View File

@ -21,7 +21,7 @@ public class FSP
{ {
lock (MainSocket) lock (MainSocket)
{ {
Debug("b", $"requesting file download: {filePath_server}\n"); Debug("b", $"requesting file download: {filePath_server}");
MainSocket.SendPackage("requesting file download".ToBytes()); MainSocket.SendPackage("requesting file download".ToBytes());
MainSocket.SendPackage(filePath_server.ToBytes()); MainSocket.SendPackage(filePath_server.ToBytes());
} }
@ -33,14 +33,14 @@ public class FSP
using System.IO.Stream fileStream = File.OpenWrite(filePath_client); using System.IO.Stream fileStream = File.OpenWrite(filePath_client);
Download_SharedCode(fileStream, true); Download_SharedCode(fileStream, true);
fileStream.Close(); fileStream.Close();
Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes\n"); Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes");
} }
public byte[] DownloadFileToMemory(string filePath_server) public byte[] DownloadFileToMemory(string filePath_server)
{ {
lock (MainSocket) lock (MainSocket)
{ {
Debug("b", $"requesting file download: {filePath_server}\n"); Debug("b", $"requesting file download: {filePath_server}");
MainSocket.SendPackage("requesting file download".ToBytes()); MainSocket.SendPackage("requesting file download".ToBytes());
MainSocket.SendPackage(filePath_server.ToBytes()); MainSocket.SendPackage(filePath_server.ToBytes());
} }
@ -53,7 +53,7 @@ public class FSP
Download_SharedCode(fileStream, false); Download_SharedCode(fileStream, false);
byte[] output = fileStream.GetBuffer(); byte[] output = fileStream.GetBuffer();
fileStream.Close(); fileStream.Close();
Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes\n"); Debug("g", $" downloaded {BytesDownloaded} of {Filesize} bytes");
return output; return output;
} }
@ -101,7 +101,7 @@ public class FSP
public void UploadFile(string filePath) public void UploadFile(string filePath)
{ {
BytesUploaded = 0; BytesUploaded = 0;
Debug("b", $"uploading file {filePath}\n"); Debug("b", $"uploading file {filePath}");
using System.IO.FileStream fileStream = File.OpenRead(filePath); using System.IO.FileStream fileStream = File.OpenRead(filePath);
Filesize = File.GetSize(filePath).ToUInt(); Filesize = File.GetSize(filePath).ToUInt();
lock (MainSocket) lock (MainSocket)
@ -129,7 +129,7 @@ public class FSP
} }
} }
fileStream.Close(); fileStream.Close();
Debug("g", $" uploaded {BytesUploaded} of {Filesize} bytes\n"); Debug("g", $" uploaded {BytesUploaded} of {Filesize} bytes");
} }
public void DownloadByManifest(string dirOnServer, string dirOnClient, bool overwrite = false, bool delete_excess = false) public void DownloadByManifest(string dirOnServer, string dirOnClient, bool overwrite = false, bool delete_excess = false)
@ -138,9 +138,9 @@ public class FSP
dirOnClient += "\\"; dirOnClient += "\\";
if (!dirOnServer.EndsWith("\\")) if (!dirOnServer.EndsWith("\\"))
dirOnServer += "\\"; dirOnServer += "\\";
Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">\n"); Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">");
var manifest = new DtsodV22(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString()); var manifest = new DtsodV22(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString());
Debug("g", $"found {manifest.Values.Count} files in manifest\n"); Debug("g", $"found {manifest.Values.Count} files in manifest");
var hasher = new Hasher(); var hasher = new Hasher();
foreach (string fileOnServer in manifest.Keys) foreach (string fileOnServer in manifest.Keys)
{ {
@ -148,16 +148,16 @@ public class FSP
Debug("b", "file <", "c", fileOnClient, "b", ">... "); Debug("b", "file <", "c", fileOnClient, "b", ">... ");
if (!File.Exists(fileOnClient)) if (!File.Exists(fileOnClient))
{ {
DebugNoTime("y", "doesn't exist\n"); DebugNoTime("y", "doesn't exist");
DownloadFile(dirOnServer + fileOnServer, fileOnClient); DownloadFile(dirOnServer + fileOnServer, fileOnClient);
} }
else if (overwrite && hasher.HashFile(fileOnClient).HashToString() != manifest[fileOnServer]) else if (overwrite && hasher.HashFile(fileOnClient).HashToString() != manifest[fileOnServer])
{ {
DebugNoTime("y", "outdated\n"); DebugNoTime("y", "outdated");
DownloadFile(dirOnServer + fileOnServer, fileOnClient); DownloadFile(dirOnServer + fileOnServer, fileOnClient);
} }
else else
DebugNoTime("g", "without changes\n"); DebugNoTime("g", "without changes");
} }
// удаление лишних файлов // удаление лишних файлов
if (delete_excess) if (delete_excess)
@ -166,7 +166,7 @@ public class FSP
{ {
if (!manifest.ContainsKey(file.Remove(0, dirOnClient.Length))) if (!manifest.ContainsKey(file.Remove(0, dirOnClient.Length)))
{ {
Debug("y", $"deleting excess file: {file}\n"); Debug("y", $"deleting excess file: {file}");
File.Delete(file); File.Delete(file);
} }
} }
@ -177,7 +177,7 @@ public class FSP
{ {
if (!dir.EndsWith("\\")) if (!dir.EndsWith("\\"))
dir += "\\"; dir += "\\";
Log($"b", $"creating manifest of {dir}\n"); Log($"b", $"creating manifest of {dir}");
StringBuilder manifestBuilder = new(); StringBuilder manifestBuilder = new();
Hasher hasher = new(); Hasher hasher = new();
if (Directory.GetFiles(dir).Contains(dir + "manifest.dtsod")) if (Directory.GetFiles(dir).Contains(dir + "manifest.dtsod"))
@ -191,7 +191,7 @@ public class FSP
manifestBuilder.Append(hash.HashToString()); manifestBuilder.Append(hash.HashToString());
manifestBuilder.Append("\";\n"); manifestBuilder.Append("\";\n");
} }
Debug($"g", $" manifest of {dir} created\n"); Debug($"g", $" manifest of {dir} created");
File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString()); File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString());
} }

View File

@ -30,7 +30,7 @@ public static class Package
else else
Thread.Sleep(5); Thread.Sleep(5);
} }
throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}\n"); throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}");
} }
// отправляет пакет // отправляет пакет