Browse Source

removed windows console commands and replaced with libs, added path exclude filter

Veloe 1 year ago
parent
commit
254df70bd0

+ 54 - 97
StringReplacer/Program.cs

@@ -1,13 +1,11 @@
-using Serilog;
+using HeyRed.Mime;
+using Serilog;
 using Serilog.Core;
-using System.Diagnostics;
 using System.Text;
+using System.Text.RegularExpressions;
 public static class Program
 {
-    private static HashSet<string> _fileNames = new HashSet<string>();
-    private static Dictionary<string, Encoding> _fileEncodings = new Dictionary<string, Encoding>();
     private static Logger _logger;
-    private static Logger _proccess_find_logger;
     private static Logger _proccess_encode_logger;
 
     static Program()
@@ -18,12 +16,6 @@ public static class Program
                 .WriteTo.Console(Serilog.Events.LogEventLevel.Debug)
                 .CreateLogger();
 
-        _proccess_find_logger = new LoggerConfiguration()
-                .MinimumLevel.Debug()
-                .WriteTo.File("proccess_find.log", Serilog.Events.LogEventLevel.Debug, fileSizeLimitBytes: 1024 * 1024, rollOnFileSizeLimit: true)
-                .WriteTo.Console(Serilog.Events.LogEventLevel.Debug)
-                .CreateLogger();
-
         _proccess_encode_logger = new LoggerConfiguration()
                 .MinimumLevel.Debug()
                 .WriteTo.File("proccess_encode.log", Serilog.Events.LogEventLevel.Debug, fileSizeLimitBytes: 1024 * 1024, rollOnFileSizeLimit: true)
@@ -35,7 +27,7 @@ public static class Program
     {
         try
         {
-            string path = "", word_Find = "", word_Replace = "", files_exts = "";
+            string path = "", word_Find = "", word_Replace = "", files_exts = "", dir_exceptions = "";
 
             if (args.Length != 0)
             {
@@ -84,6 +76,14 @@ public static class Program
                             _logger.Information($"Files extentions: {files_exts}");
                             argIndex++;
                             break;
+                        case "-i":
+                            if (!string.IsNullOrEmpty(dir_exceptions))
+                                _logger.Warning("Duplicating argument {0} {1}", args[argIndex], args[argIndex + 1]);
+                            dir_exceptions = args[++argIndex];
+
+                            _logger.Information($"Dir exceptions: {dir_exceptions}");
+                            argIndex++;
+                            break;
                         default:
                             _logger.Warning("Skipped unrecognized argument {0}", argIndex);
                             argIndex++;
@@ -128,51 +128,52 @@ public static class Program
             if (string.IsNullOrEmpty(files_exts))
                 files_exts = "*.pas *.dfm *.dpr";
 
+            if (string.IsNullOrEmpty(dir_exceptions))
+                dir_exceptions = $"_\\S*\\{Path.DirectorySeparatorChar}";
+
             Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+            var extentions = files_exts.Split(' ').ToArray();
 
-            Process processFind = new Process();
-            ProcessStartInfo startInfoFind = new ProcessStartInfo();
-            startInfoFind.WindowStyle = ProcessWindowStyle.Hidden;
-            startInfoFind.RedirectStandardOutput = true;
-            startInfoFind.WorkingDirectory = path;
-            startInfoFind.FileName = "cmd.exe";
-            startInfoFind.Arguments = $"/C findstr /s /i  {word_Find} {files_exts}";
-            processFind.StartInfo = startInfoFind;
-            processFind.OutputDataReceived += ProcessFind_OutputDataReceived;
-            processFind.Start();
-            processFind.BeginOutputReadLine();
-
-            processFind.WaitForExit();
-            processFind.CancelOutputRead();
-            processFind.OutputDataReceived -= ProcessFind_OutputDataReceived;
-            processFind.Close();
-
-            Process processEncode = new Process();
-            ProcessStartInfo startInfoEncode = new ProcessStartInfo();
-            startInfoEncode.WindowStyle = ProcessWindowStyle.Hidden;
-            startInfoEncode.RedirectStandardOutput = true;
-            startInfoEncode.WorkingDirectory = path;
-            startInfoEncode.FileName = "cmd.exe";
-            startInfoEncode.Arguments = $"/C \"C:\\Program Files\\Git\\usr\\bin\\file.exe\" --mime-encoding  {string.Join(' ', _fileNames)}";
-            processEncode.StartInfo = startInfoEncode;
-            processEncode.OutputDataReceived += ProcessEncode_OutputDataReceived;
-            processEncode.Start();
-            processEncode.BeginOutputReadLine();
-
-            processEncode.WaitForExit();
-            processEncode.CancelOutputRead();
-            processEncode.OutputDataReceived -= ProcessEncode_OutputDataReceived;
-            processEncode.Close();
-
-            foreach (var filename in _fileNames)
-            {
-                StringBuilder stringBuilder = new StringBuilder();
-                stringBuilder.Append(File.ReadAllText($"{path}/{filename}", _fileEncodings[filename]));
-                stringBuilder.Replace(word_Find, word_Replace);
-                File.WriteAllText($"{path}/{filename}", stringBuilder.ToString(), _fileEncodings[filename]);
+            IEnumerable<string> files = Enumerable.Empty<string>();
 
-                _logger.Information($"Replaced in {path}\\{filename}");
+            foreach(var extention in extentions)
+            {
+                files = files.Union(Directory.EnumerateFiles(path, extention, SearchOption.AllDirectories));
             }
+
+            if (!string.IsNullOrEmpty(dir_exceptions))
+                files = files.Where(f=>!Regex.IsMatch(f,dir_exceptions));
+
+            using (var magic = new Magic(MagicOpenFlags.MAGIC_MIME_ENCODING))
+                foreach (var file in files)
+                {
+                    var encodingString = magic.Read(file);
+                    _proccess_encode_logger.Information("{0}: {1}",file, encodingString);
+                    Encoding encoding = Encoding.GetEncoding("windows-1251");
+
+                    switch (encodingString)
+                    {
+                        case "utf-8":
+                            encoding = Encoding.UTF8;
+                            break;
+                        case "us-ascii":
+                        case "iso-8859-1":
+                            encoding = Encoding.GetEncoding("windows-1251");
+                            break;
+                        default:
+                            _logger.Warning("Encoding not recognized for {0}. Using {1} as default", file, encoding.HeaderName);
+                            break;
+                    }
+
+                    var content = File.ReadAllText(file, encoding);
+
+                    if (Regex.IsMatch(content,$"\\b{word_Find}\\b"))
+                    {
+                        File.WriteAllText(file, Regex.Replace(content, $"\\b{word_Find}\\b", word_Replace), encoding);
+                        _logger.Information("Replaced in {0}; mime-encoding: {1}; used encoding: {2}", file, encodingString, encoding.HeaderName);
+                    }
+                }
+
         }
         catch (Exception ex)
         {
@@ -193,48 +194,4 @@ public static class Program
 
     private static bool ValidatePath(string path, bool throwException = false) => !string.IsNullOrEmpty(path) && Directory.Exists(path) || (throwException ? throw new DirectoryNotFoundException(string.Format("Path is not valid {0}", path)) : false);
 
-    private static void ProcessEncode_OutputDataReceived(object sender, DataReceivedEventArgs e)
-    {
-        var filepath = e.Data;
-        if (!string.IsNullOrEmpty(filepath))
-        {
-            _proccess_encode_logger.Information(filepath);
-            var index = filepath.IndexOf(':');
-            filepath = filepath.Substring(0, index != -1 ? index : 0);
-
-            if (!string.IsNullOrEmpty(filepath))
-            {
-
-                var encoding = e.Data?.Substring(index + 1).Trim();
-
-                if (!string.IsNullOrEmpty(encoding))
-                {
-                    switch (encoding)
-                    {
-                        case "utf-8":
-                            _fileEncodings.Add(filepath, Encoding.UTF8);
-                            break;
-                        case "us-ascii":
-                        case "iso-8859-1":
-                            _fileEncodings.Add(filepath, Encoding.GetEncoding("windows-1251"));
-                            break;
-                    }
-                }
-            }
-        }
-    }
-
-    private static void ProcessFind_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
-    {
-        var filepath = e.Data;
-        if (!string.IsNullOrEmpty(filepath))
-        {
-            _proccess_find_logger.Information(filepath);
-            var index = filepath.IndexOf(':');
-            filepath = filepath.Substring(0, index != -1 ? index : 0);
-
-            if (!string.IsNullOrEmpty(filepath))
-                _fileNames.Add(filepath);
-        }
-    }
 }

+ 8 - 0
StringReplacer/Properties/launchSettings.json

@@ -0,0 +1,8 @@
+{
+  "profiles": {
+    "StringReplacer": {
+      "commandName": "Project",
+      "commandLineArgs": "-p C:\\Users\\Veloe\\Desktop\\TestFolder1 -e *.pas"
+    }
+  }
+}

+ 4 - 3
StringReplacer/StringReplacer.csproj

@@ -1,15 +1,16 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
 
   <PropertyGroup>
     <OutputType>Exe</OutputType>
     <TargetFramework>net7.0</TargetFramework>
     <ImplicitUsings>enable</ImplicitUsings>
     <Nullable>enable</Nullable>
-    <AssemblyVersion>1.0.0.59</AssemblyVersion>
-    <FileVersion>1.0.0.59</FileVersion>
+    <AssemblyVersion>1.1.0.10</AssemblyVersion>
+    <FileVersion>1.1.0.10</FileVersion>
   </PropertyGroup>
 
   <ItemGroup>
+    <PackageReference Include="Mime" Version="3.6.0" />
     <PackageReference Include="Serilog" Version="3.1.1" />
     <PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
     <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />