VSCodeTask

Download SSL Certificates
Sort Subtasks of Markdown files
Test BioRad
EAF CopyDirectories
json to Markdown
Sort Day 2024 Q2
GitRemoteRemove
Handle directoryInfo.LinkTarget better
Remove StartAt
Handle directoryInfo.LinkTarget
This commit is contained in:
Mike Phares 2024-08-02 13:32:23 -07:00
parent 1cd20fa08b
commit 2923e86a94
23 changed files with 1211 additions and 731 deletions

1
.gitignore vendored
View File

@ -335,3 +335,4 @@ ASALocalRun/
.extensions-vscode .extensions-vscode
.extensions-vscode-oss .extensions-vscode-oss
.extensions-vscode-insiders .extensions-vscode-insiders
.vscode/.UserSecrets/secrets.json

10
.vscode/mklink.md vendored
View File

@ -18,7 +18,11 @@ mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.kanbn" "D:\5-Other-Small\Kanban
del "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode" del "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode"
del "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-oss" del "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-oss"
del "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-insiders" del "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-insiders"
mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode" "C:\Users\phares\.vscode\extensions\ifx.type-script-helper-1.6.2" mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode" "C:\Users\phares\.vscode\extensions\ifx.type-script-helper-1.6.3"
mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-oss" "C:\Users\phares\.vscode-oss\extensions\ifx.type-script-helper-1.6.2" mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-oss" "C:\Users\phares\.vscode-oss\extensions\ifx.type-script-helper-1.6.3"
mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-insiders" "C:\Users\phares\.vscode-insiders\extensions\ifx.type-script-helper-1.6.2" mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-insiders" "C:\Users\phares\.vscode-insiders\extensions\ifx.type-script-helper-1.6.3"
```
```bash Thu Jul 18 2024 13:47:40 GMT-0700 (Mountain Standard Time)
mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.vscode\.UserSecrets" "L:\Git\Notes-User-Secrets\.UserSecrets\8da397d4-13ec-4576-9722-3c79cad25563"
``` ```

View File

@ -31,6 +31,7 @@
"onenote", "onenote",
"pged", "pged",
"Phares", "Phares",
"Reparse",
"Rijndael", "Rijndael",
"Serilog", "Serilog",
"SUBM", "SUBM",

96
.vscode/tasks.json vendored
View File

@ -105,94 +105,50 @@
], ],
"problemMatcher": "$msCompile" "problemMatcher": "$msCompile"
}, },
{
"label": "File-Folder-Helper AOT s H Run Data Repository",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\Metrology\\Run Data Repository'",
"problemMatcher": []
},
{ {
"label": "File-Folder-Helper AOT s J Verdaccio", "label": "File-Folder-Helper AOT s J Verdaccio",
"type": "shell", "type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s J 'L:/Verdaccio/storage'", "command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe",
"problemMatcher": [] "args": [
}, "s",
{ "J",
"label": "File-Folder-Helper AOT s M Self .Kanbn Tasks", "L:/Verdaccio/storage",
"type": "shell", ],
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s M L:/DevOps/Mesa_FI/File-Folder-Helper L:/DevOps/Mesa_FI/File-Folder-Helper/.kanbn/tasks",
"problemMatcher": [] "problemMatcher": []
}, },
{ {
"label": "File-Folder-Helper AOT s S BaGet", "label": "File-Folder-Helper AOT s S BaGet",
"type": "shell", "type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s S 'L:/BaGet/packages'", "command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe",
"args": [
"s",
"S",
"L:/BaGet/packages",
],
"problemMatcher": [] "problemMatcher": []
}, },
{ {
"label": "File-Folder-Helper AOT s X SortCodeMethods", "label": "File-Folder-Helper AOT s X SortCodeMethods",
"type": "shell", "type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s X L:/DevOps/Mesa_FI/File-Folder-Helper Day-Helper-2024-01-08 L:/DevOps/Mesa_FI/File-Folder-Helper/Day/2024-Q2", "command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe",
"problemMatcher": [] "args": [
}, "s",
{ "X",
"label": "File-Folder-Helper AOT s H MET08ANLYSDIFAAST230", "L:/DevOps/Mesa_FI/File-Folder-Helper",
"type": "shell", "Day-Helper-2024-01-08",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\Metrology\\Run Data Repository\\MET08ANLYSDIFAAST230\\Source\\MET08ANLYSDIFAAST230'", "L:/DevOps/Mesa_FI/File-Folder-Helper/Helpers"
"problemMatcher": [] ],
},
{
"label": "File-Folder-Helper AOT s H MET08DDUPSFS6420",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\Metrology\\Run Data Repository\\MET08DDUPSFS6420\\Source\\MET08DDUPSFS6420'",
"problemMatcher": []
},
{
"label": "File-Folder-Helper AOT s H MET08DDUPSP1TBI",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\Metrology\\Run Data Repository\\MET08DDUPSP1TBI\\Source\\MET08DDUPSP1TBI'",
"problemMatcher": []
},
{
"label": "File-Folder-Helper AOT s H MET08RESIHGCV",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\Metrology\\Run Data Repository\\MET08RESIHGCV\\Source\\MET08RESIHGCV'",
"problemMatcher": []
},
{
"label": "File-Folder-Helper AOT s H MET08RESIMAPCDE",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\Metrology\\Run Data Repository\\MET08RESIMAPCDE\\Source\\MET08RESIMAPCDE'",
"problemMatcher": []
},
{
"label": "File-Folder-Helper AOT s H MET08RESISRP2100",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\Metrology\\Run Data Repository\\MET08RESISRP2100\\Source\\MET08RESISRP2100'",
"problemMatcher": []
},
{
"label": "File-Folder-Helper AOT s H MET08THFTIRQS408M",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\Metrology\\Run Data Repository\\MET08THFTIRQS408M\\Source\\MET08THFTIRQS408M'",
"problemMatcher": []
},
{
"label": "File-Folder-Helper AOT s H MET08THFTIRSTRATUS",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\Metrology\\Run Data Repository\\MET08THFTIRSTRATUS\\Source\\MET08THFTIRSTRATUS'",
"problemMatcher": []
},
{
"label": "File-Folder-Helper AOT s H WaferCounter",
"type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s H '\\\\messa01ec.infineon.com\\apps\\WaferCounter\\BackupFiles'",
"problemMatcher": [] "problemMatcher": []
}, },
{ {
"label": "File-Folder-Helper AOT s F Staging _Logs", "label": "File-Folder-Helper AOT s F Staging _Logs",
"type": "shell", "type": "shell",
"command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe s F '\\\\messv02ecc1.ec.local\\EC_EAFLog\\Staging\\_ Logs'", "command": "L:/DevOps/Mesa_FI/File-Folder-Helper/bin/Release/net8.0/win-x64/publish/File-Folder-Helper.exe",
"args": [
"s",
"F",
"'\\\\messv02ecc1.ec.local\\EC_EAFLog\\Staging\\_ Logs'",
],
"problemMatcher": [] "problemMatcher": []
}, },
{ {

View File

@ -1,3 +1,4 @@
using File_Folder_Helper.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Text; using System.Text;
@ -9,22 +10,6 @@ namespace File_Folder_Helper.Day;
internal static partial class Helper20240106 internal static partial class Helper20240106
{ {
private record Host([property: JsonPropertyName("a")] string? Id,
[property: JsonPropertyName("b")] string? Colon,
[property: JsonPropertyName("c")] string? Hyphen,
[property: JsonPropertyName("d")] string? Line,
[property: JsonPropertyName("e")] string? Count,
[property: JsonPropertyName("f")] string? Segments,
[property: JsonPropertyName("g")] string? Type,
[property: JsonPropertyName("h")] string? Device,
[property: JsonPropertyName("i")] string? Name);
[JsonSourceGenerationOptions(WriteIndented = true, AllowTrailingCommas = true)]
[JsonSerializable(typeof(Host[]))]
private partial class HostSourceGenerationContext : JsonSerializerContext
{
}
private record Record(string Key, Dictionary<string, string> KeyValuePairs); private record Record(string Key, Dictionary<string, string> KeyValuePairs);
[JsonSourceGenerationOptions(WriteIndented = true)] [JsonSourceGenerationOptions(WriteIndented = true)]

View File

@ -13,6 +13,40 @@ internal static partial class Helper20240403
string Pattern, string Pattern,
string Primary); string Primary);
private static void AlertIfNewDeviceIsConnected(DynamicHostConfigurationProtocolConfiguration dynamicHostConfigurationProtocolConfiguration, ILogger<Worker> logger)
{
string[] files = Directory.GetFiles(dynamicHostConfigurationProtocolConfiguration.Directory, dynamicHostConfigurationProtocolConfiguration.Pattern, SearchOption.TopDirectoryOnly);
string? match = GetMatch(dynamicHostConfigurationProtocolConfiguration, files);
if (string.IsNullOrEmpty(match))
throw new NotSupportedException($"{dynamicHostConfigurationProtocolConfiguration.Primary} doesn't exist!");
ReadOnlyDictionary<string, int> keyToCounts = GetKeyToCounts(dynamicHostConfigurationProtocolConfiguration, files);
foreach (KeyValuePair<string, int> keyToCount in keyToCounts)
{
if (keyToCount.Value < 2)
continue;
logger.LogInformation("{Key}: {Count}", keyToCount.Key, keyToCount.Value);
}
ReadOnlyDictionary<string, ReadOnlyDictionary<string, ReadOnlyCollection<string>>> keyValuePairs = GetKeyValuePairs(dynamicHostConfigurationProtocolConfiguration, files);
foreach (KeyValuePair<string, ReadOnlyDictionary<string, ReadOnlyCollection<string>>> keyValuePair in keyValuePairs)
{
if (!keyValuePair.Key.EndsWith(dynamicHostConfigurationProtocolConfiguration.Primary))
continue;
}
}
internal static void AlertIfNewDeviceIsConnected(ILogger<Worker> logger, List<string> args)
{
string ignore = args[6];
string pattern = args[2];
string primary = args[3];
string keyIndex = args[5];
string directory = args[0];
logger.LogInformation(directory);
string[] columns = args[4].Split('|');
DynamicHostConfigurationProtocolConfiguration dynamicHostConfigurationProtocolConfiguration = new(columns, directory, ignore, int.Parse(keyIndex), pattern, primary);
AlertIfNewDeviceIsConnected(dynamicHostConfigurationProtocolConfiguration, logger);
}
private static string? GetMatch(DynamicHostConfigurationProtocolConfiguration dynamicHostConfigurationProtocolConfiguration, string[] files) private static string? GetMatch(DynamicHostConfigurationProtocolConfiguration dynamicHostConfigurationProtocolConfiguration, string[] files)
{ {
string? result = null; string? result = null;
@ -114,38 +148,4 @@ internal static partial class Helper20240403
return results; return results;
} }
private static void AlertIfNewDeviceIsConnected(DynamicHostConfigurationProtocolConfiguration dynamicHostConfigurationProtocolConfiguration, ILogger<Worker> logger)
{
string[] files = Directory.GetFiles(dynamicHostConfigurationProtocolConfiguration.Directory, dynamicHostConfigurationProtocolConfiguration.Pattern, SearchOption.TopDirectoryOnly);
string? match = GetMatch(dynamicHostConfigurationProtocolConfiguration, files);
if (string.IsNullOrEmpty(match))
throw new NotSupportedException($"{dynamicHostConfigurationProtocolConfiguration.Primary} doesn't exist!");
ReadOnlyDictionary<string, int> keyToCounts = GetKeyToCounts(dynamicHostConfigurationProtocolConfiguration, files);
foreach (KeyValuePair<string, int> keyToCount in keyToCounts)
{
if (keyToCount.Value < 2)
continue;
logger.LogInformation("{Key}: {Count}", keyToCount.Key, keyToCount.Value);
}
ReadOnlyDictionary<string, ReadOnlyDictionary<string, ReadOnlyCollection<string>>> keyValuePairs = GetKeyValuePairs(dynamicHostConfigurationProtocolConfiguration, files);
foreach (KeyValuePair<string, ReadOnlyDictionary<string, ReadOnlyCollection<string>>> keyValuePair in keyValuePairs)
{
if (!keyValuePair.Key.EndsWith(dynamicHostConfigurationProtocolConfiguration.Primary))
continue;
}
}
internal static void AlertIfNewDeviceIsConnected(ILogger<Worker> logger, List<string> args)
{
string ignore = args[6];
string pattern = args[2];
string primary = args[3];
string keyIndex = args[5];
string directory = args[0];
logger.LogInformation(directory);
string[] columns = args[4].Split('|');
DynamicHostConfigurationProtocolConfiguration dynamicHostConfigurationProtocolConfiguration = new(columns, directory, ignore, int.Parse(keyIndex), pattern, primary);
AlertIfNewDeviceIsConnected(dynamicHostConfigurationProtocolConfiguration, logger);
}
} }

View File

@ -21,27 +21,6 @@ internal static partial class Helper20240404
string RegularExpressionPattern, string RegularExpressionPattern,
string SearchPattern); string SearchPattern);
private static MetaData? GetMetaData(CommaSeparatedValuesConfiguration commaSeparatedValuesConfiguration, string fileNameWithoutExtension)
{
MetaData? result;
Match match = Regex.Match(fileNameWithoutExtension, commaSeparatedValuesConfiguration.RegularExpressionPattern);
if (!match.Success || match.Groups.Count != commaSeparatedValuesConfiguration.RegularExpressionGroupCount)
result = null;
else
{
int deviceId = int.Parse(match.Groups["DeviceId"].Value);
int deviceNumber = int.Parse(match.Groups["DeviceNumber"].Value);
result = new(deviceId,
match.Groups["DeviceType"].Value,
deviceNumber,
match.Groups["DescriptionName"].Value,
match.Groups["DescriptionTest"].Value,
match.Groups["Frequency"].Value,
match.Groups["Date"].Value);
}
return result;
}
private static void ParseCSV(CommaSeparatedValuesConfiguration commaSeparatedValuesConfiguration, ILogger<Worker> logger) private static void ParseCSV(CommaSeparatedValuesConfiguration commaSeparatedValuesConfiguration, ILogger<Worker> logger)
{ {
string line; string line;
@ -93,4 +72,25 @@ internal static partial class Helper20240404
ParseCSV(commaSeparatedValuesConfiguration, logger); ParseCSV(commaSeparatedValuesConfiguration, logger);
} }
private static MetaData? GetMetaData(CommaSeparatedValuesConfiguration commaSeparatedValuesConfiguration, string fileNameWithoutExtension)
{
MetaData? result;
Match match = Regex.Match(fileNameWithoutExtension, commaSeparatedValuesConfiguration.RegularExpressionPattern);
if (!match.Success || match.Groups.Count != commaSeparatedValuesConfiguration.RegularExpressionGroupCount)
result = null;
else
{
int deviceId = int.Parse(match.Groups["DeviceId"].Value);
int deviceNumber = int.Parse(match.Groups["DeviceNumber"].Value);
result = new(deviceId,
match.Groups["DeviceType"].Value,
deviceNumber,
match.Groups["DescriptionName"].Value,
match.Groups["DescriptionTest"].Value,
match.Groups["Frequency"].Value,
match.Groups["Date"].Value);
}
return result;
}
} }

View File

@ -236,40 +236,6 @@ internal static partial class Helper20240517
{ {
} }
private static ReadOnlyCollection<(string, string)> GetAggregationLines(string harFile)
{
List<(string, string)> results = [];
if (!File.Exists(harFile))
throw new Exception();
string lastUrl = string.Empty;
string text = "\"text\": \"{";
string[] lines = File.ReadAllLines(harFile);
foreach (string line in lines)
{
if (line.Contains("\"url\": \""))
lastUrl = line;
if (!line.Contains(text))
continue;
if (!line.Contains("aggregations"))
continue;
if (lastUrl.Contains("search?asset=NONE"))
continue;
results.Add(new(lastUrl, line.Trim()[(text.Length - 1)..^1].Replace("\\\"", "\"")));
lastUrl = string.Empty;
}
return new(results);
}
private static void SaveAmazon(IReadOnlyList<Datum> data, string personIdFile)
{
string json;
Dictionary<string, Datum> keyValuePairs = [];
foreach (Datum datum in data)
_ = keyValuePairs.TryAdd(datum.Name.Split('.')[0], datum);
json = JsonSerializer.Serialize(keyValuePairs, DictionaryDatumGenerationContext.Default.DictionaryStringDatum);
File.WriteAllText(personIdFile, json);
}
private static void SaveAmazon(string destination, string harFile) private static void SaveAmazon(string destination, string harFile)
{ {
string offset; string offset;
@ -331,4 +297,38 @@ internal static partial class Helper20240517
logger?.LogInformation("{harFiles} count", harFiles.Length); logger?.LogInformation("{harFiles} count", harFiles.Length);
} }
private static void SaveAmazon(IReadOnlyList<Datum> data, string personIdFile)
{
string json;
Dictionary<string, Datum> keyValuePairs = [];
foreach (Datum datum in data)
_ = keyValuePairs.TryAdd(datum.Name.Split('.')[0], datum);
json = JsonSerializer.Serialize(keyValuePairs, DictionaryDatumGenerationContext.Default.DictionaryStringDatum);
File.WriteAllText(personIdFile, json);
}
private static ReadOnlyCollection<(string, string)> GetAggregationLines(string harFile)
{
List<(string, string)> results = [];
if (!File.Exists(harFile))
throw new Exception();
string lastUrl = string.Empty;
string text = "\"text\": \"{";
string[] lines = File.ReadAllLines(harFile);
foreach (string line in lines)
{
if (line.Contains("\"url\": \""))
lastUrl = line;
if (!line.Contains(text))
continue;
if (!line.Contains("aggregations"))
continue;
if (lastUrl.Contains("search?asset=NONE"))
continue;
results.Add(new(lastUrl, line.Trim()[(text.Length - 1)..^1].Replace("\\\"", "\"")));
lastUrl = string.Empty;
}
return new(results);
}
} }

View File

@ -1,19 +1,21 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Collections.ObjectModel;
namespace File_Folder_Helper.Day; namespace File_Folder_Helper.Day;
internal static partial class Helper20240623 internal static partial class Helper20240623
{ {
private record SubTaskLine(string Text, bool Done, long? Ticks, int? Line);
private record Record(int? CodeInsidersLine, string File, string[] Lines, int? StopLine, int? SubTasksLine); private record Record(int? CodeInsidersLine, string File, string[] Lines, int? StopLine, int? SubTasksLine);
private static List<Record> GetRecords(string sourceDirectory, string searchPattern, string codeInsiders, string subTasks) private static List<Record> GetRecords(string sourceDirectory, string searchPattern, string codeInsiders, string subTasks)
{ {
List<Record> results = []; List<Record> results = [];
int? stopLine; int? stopLine;
string[] lines;
int? subTasksLine; int? subTasksLine;
int? codeInsidersLine; int? codeInsidersLine;
string[] lines;
string[] files = Directory.GetFiles(sourceDirectory, searchPattern, SearchOption.AllDirectories); string[] files = Directory.GetFiles(sourceDirectory, searchPattern, SearchOption.AllDirectories);
foreach (string file in files) foreach (string file in files)
{ {
@ -52,24 +54,60 @@ internal static partial class Helper20240623
return results; return results;
} }
private static ReadOnlyCollection<SubTaskLine> GetSubTasks(string subTasks, string[] tasks, bool? foundDone, string fallbackLine, FileInfo fileInfo)
{
List<SubTaskLine> results = [];
string line;
bool doneValue;
string? h1 = null;
bool foundSubTasks = false;
int tasksZeroLength = tasks[0].Length;
string[] lines = File.ReadAllLines(fileInfo.FullName);
for (int i = 0; i < lines.Length; i++)
{
line = lines[i];
if (line.StartsWith("# "))
h1 = line[2..];
if (!foundSubTasks && line == subTasks)
foundSubTasks = true;
if (!foundSubTasks)
continue;
if (line.Length <= tasksZeroLength || !line.StartsWith(tasks[0]) || line[tasksZeroLength] is not ' ' and not 'x' || line[tasksZeroLength + 1] != ']')
continue;
doneValue = foundDone is not null && foundDone.Value;
results.Add(new($" {line}", doneValue, fileInfo.LastWriteTime.Ticks, i));
}
doneValue = foundDone is not null && foundDone.Value;
if (h1 is null)
results.Add(new(fallbackLine, doneValue, fileInfo.LastWriteTime.Ticks, Line: null));
else
results.Add(new(foundDone is null || !foundDone.Value ? $"- [ ] {fileInfo.LastWriteTime.Ticks} ~~~ {h1}" : $"- [x] {fileInfo.LastWriteTime.Ticks} ~~~ {h1}", doneValue, fileInfo.LastWriteTime.Ticks, Line: 0));
return new(results);
}
internal static void UpdateSubTasksInMarkdownFiles(ILogger<Worker> logger, List<string> args) internal static void UpdateSubTasksInMarkdownFiles(ILogger<Worker> logger, List<string> args)
{ {
int lineCheck; int lineCheck;
bool doneValue;
bool? foundDone; bool? foundDone;
FileInfo fileInfo;
string[] newLines;
string[] segments; string[] segments;
List<string> lines; List<string> lines;
string fallbackLine;
string[] indexLines; string[] indexLines;
string checkDirectory; string checkDirectory;
string done = args[7]; string done = args[7];
List<string> indexFiles; List<string> indexFiles;
string subTasks = args[3]; string subTasks = args[3];
List<string> newLines = [];
List<string> oldLines = []; List<string> oldLines = [];
string indexFile = args[5]; string indexFile = args[5];
string searchPattern = args[2]; string searchPattern = args[2];
string directoryFilter = args[8]; string directoryFilter = args[8];
string[] tasks = args[6].Split(','); string[] tasks = args[6].Split(',');
string codeInsiders = $"{args[4]} \""; string codeInsiders = $"{args[4]} \"";
List<SubTaskLine> allSubTaskLines = [];
ReadOnlyCollection<SubTaskLine> subTaskLines;
string sourceDirectory = Path.GetFullPath(args[0]); string sourceDirectory = Path.GetFullPath(args[0]);
List<Record> records = GetRecords(sourceDirectory, searchPattern, codeInsiders, subTasks); List<Record> records = GetRecords(sourceDirectory, searchPattern, codeInsiders, subTasks);
foreach (Record record in from l in records orderby l.SubTasksLine is null, l.CodeInsidersLine is null select l) foreach (Record record in from l in records orderby l.SubTasksLine is null, l.CodeInsidersLine is null select l)
@ -106,36 +144,47 @@ internal static partial class Helper20240623
} }
} }
foundDone = null; foundDone = null;
newLines.Clear();
oldLines.Clear(); oldLines.Clear();
allSubTaskLines.Clear();
indexLines = File.ReadAllLines(indexFiles[0]); indexLines = File.ReadAllLines(indexFiles[0]);
checkDirectory = Path.GetDirectoryName(indexFiles[0]) ?? throw new Exception();
for (int i = 0; i < indexLines.Length; i++) for (int i = 0; i < indexLines.Length; i++)
{ {
if (indexLines[i] == done) if (indexLines[i] == done)
foundDone = true; foundDone = true;
segments = indexLines[i].Split(tasks[1]); segments = indexLines[i].Split(tasks[1]);
doneValue = foundDone is not null && foundDone.Value;
if (segments.Length > 2 || !segments[0].StartsWith(tasks[0])) if (segments.Length > 2 || !segments[0].StartsWith(tasks[0]))
continue; continue;
if (foundDone is null || !foundDone.Value) fallbackLine = foundDone is null || !foundDone.Value ? $"- [ ] {segments[0][tasks[0].Length..]}" : $"- [x] {segments[0][tasks[0].Length..]}";
newLines.Add($"- [ ] {segments[0][tasks[0].Length..]}"); fileInfo = new(Path.GetFullPath(Path.Combine(checkDirectory, segments[1][..^1])));
else if (!fileInfo.Exists)
newLines.Add($"- [x] {segments[0][tasks[0].Length..]}"); {
allSubTaskLines.Add(new(fallbackLine, doneValue, Ticks: null, Line: null));
continue;
}
subTaskLines = GetSubTasks(subTasks, tasks, doneValue, fallbackLine, fileInfo);
for (int j = subTaskLines.Count - 1; j >= 0; j--)
allSubTaskLines.Add(subTaskLines[j]);
} }
if (newLines.Count == 0) if (allSubTaskLines.Count == 0)
continue; continue;
lineCheck = 0; lineCheck = 0;
newLines.Insert(0, string.Empty);
for (int i = record.SubTasksLine.Value + 1; i < record.StopLine.Value - 1; i++) for (int i = record.SubTasksLine.Value + 1; i < record.StopLine.Value - 1; i++)
oldLines.Add(record.Lines[i]); oldLines.Add(record.Lines[i]);
if (newLines.Count == oldLines.Count) if (allSubTaskLines.Any(l => l.Ticks is null))
newLines = (from l in allSubTaskLines select l.Text).ToArray();
else
newLines = (from l in allSubTaskLines orderby l.Done descending, l.Ticks, l.Line select l.Text).ToArray();
if (newLines.Length == oldLines.Count)
{ {
for (int i = 0; i < newLines.Count; i++) for (int i = 0; i < newLines.Length; i++)
{ {
if (newLines[i] != record.Lines[record.SubTasksLine.Value + 1 + i]) if (newLines[i] != record.Lines[record.SubTasksLine.Value + 1 + i])
continue; continue;
lineCheck++; lineCheck++;
} }
if (lineCheck == newLines.Count) if (lineCheck == newLines.Length)
continue; continue;
} }
checkDirectory = Path.Combine(checkDirectory, DateTime.Now.Ticks.ToString()); checkDirectory = Path.Combine(checkDirectory, DateTime.Now.Ticks.ToString());
@ -147,8 +196,9 @@ internal static partial class Helper20240623
lines.RemoveAt(i); lines.RemoveAt(i);
if (record.StopLine.Value == record.Lines.Length && lines[^1].Length == 0) if (record.StopLine.Value == record.Lines.Length && lines[^1].Length == 0)
lines.RemoveAt(lines.Count - 1); lines.RemoveAt(lines.Count - 1);
for (int i = 0; i < newLines.Count; i++) for (int i = 0; i < newLines.Length; i++)
lines.Insert(record.SubTasksLine.Value + 1 + i, newLines[i]); lines.Insert(record.SubTasksLine.Value + 1 + i, newLines[i]);
lines.Insert(record.SubTasksLine.Value + 1, string.Empty);
File.WriteAllLines(record.File, lines); File.WriteAllLines(record.File, lines);
} }
} }

View File

@ -73,7 +73,7 @@ internal static partial class Helper20240624
} }
} }
internal static void MoveUpOndDirectory(ILogger<Worker> logger, List<string> args) internal static void MoveUpOneDirectory(ILogger<Worker> logger, List<string> args)
{ {
string searchPattern = args[2]; string searchPattern = args[2];
string sourceDirectory = Path.GetFullPath(args[0]); string sourceDirectory = Path.GetFullPath(args[0]);

View File

@ -0,0 +1,79 @@
using Microsoft.Extensions.Logging;
using System.Collections.ObjectModel;
namespace File_Folder_Helper.Day;
internal static partial class Helper20240711
{
internal static void GitRemoteRemove(ILogger<Worker> logger, List<string> args)
{
string line;
string[] lines;
bool branchCheck;
bool remoteCheck;
string? directory;
string? parentDirectory;
string parentDirectoryName;
string branchName = args[8];
string searchPattern = args[2];
string remoteToAddUrl = args[6];
string remoteToRemove = args[3];
string remoteToAddName = args[5];
ReadOnlyCollection<string> messages;
string remoteToRemoveFilter = args[4];
string sourceDirectory = Path.GetFullPath(args[0]);
string lastRemoteSegment = remoteToRemove.Split('/')[^1];
string extension = args[7].Length > 2 ? args[7] : string.Empty;
string[] files = Directory.EnumerateFiles(sourceDirectory, searchPattern, new EnumerationOptions() { IgnoreInaccessible = true, RecurseSubdirectories = true, AttributesToSkip = FileAttributes.None }).ToArray();
logger.LogInformation("Found {files} file(s)", files.Length);
foreach (string file in files)
{
branchCheck = false;
remoteCheck = false;
lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
{
line = lines[i];
if (!line.Contains(remoteToRemove))
continue;
if (!lines[i - 1].Contains(remoteToRemoveFilter))
continue;
remoteCheck = true;
break;
}
for (int i = 0; i < lines.Length; i++)
{
line = lines[i];
if (!line.Contains(branchName))
continue;
branchCheck = true;
break;
}
if (!remoteCheck)
continue;
directory = Path.GetDirectoryName(file);
if (directory is null)
continue;
parentDirectory = Path.GetDirectoryName(directory);
if (parentDirectory is null)
continue;
parentDirectoryName = Path.GetFileName(parentDirectory).ToLower();
messages = Helpers.HelperGit.RemoteRemove(parentDirectory, lastRemoteSegment, CancellationToken.None);
foreach (string message in messages)
logger.LogInformation("{function} => {parentDirectoryName}: [{message}]", nameof(Helpers.HelperGit.RemoteRemove), parentDirectoryName, message);
messages = Helpers.HelperGit.RemoteAdd(parentDirectory, remoteToAddName, $"{remoteToAddUrl}{parentDirectoryName}{extension}", CancellationToken.None);
foreach (string message in messages)
logger.LogInformation("{function} => {parentDirectoryName}: [{message}]", nameof(Helpers.HelperGit.RemoteAdd), parentDirectoryName, message);
if (!branchCheck)
continue;
try
{ messages = Helpers.HelperGit.PushBranch(parentDirectory, remoteToAddName, branchName, CancellationToken.None); }
catch (Exception ex)
{ messages = new([ex.Message]); }
foreach (string message in messages)
logger.LogInformation("{function} => {parentDirectoryName}: [{message}]", nameof(Helpers.HelperGit.PushBranch), parentDirectoryName, message);
}
}
}

View File

@ -0,0 +1,84 @@
using File_Folder_Helper.Models;
using Microsoft.Extensions.Logging;
using System.Collections.ObjectModel;
using System.Text.Json;
namespace File_Folder_Helper.Day;
internal static partial class Helper20240718
{
private static Host[] GetHosts(ILogger<Worker> logger, string file)
{
Host[] results;
string lines = File.ReadAllText(file);
string json = $"[{lines.Replace("\r\n", ",")}]";
logger.LogDebug(lines);
results = JsonSerializer.Deserialize(json, HostSourceGenerationContext.Default.HostArray) ?? throw new NullReferenceException();
return results;
}
private static ReadOnlyCollection<string> GetLines(Host[] hosts, string title, string wired)
{
List<string> results = [$"# {title}", string.Empty, "```mermaid", "flowchart TB", $" subgraph {title}"];
int id;
string check;
List<int> distinct = [];
string newLine = $"{Environment.NewLine} ";
foreach (Host host in hosts)
{
if (host.Id is null || host.Hyphen is null || host.Device is null || host.Name is null || host.Hyphen.Length != 17)
continue;
if (!int.TryParse(host.Id, out id))
throw new NotSupportedException($"{host.Id} is not a number");
if (distinct.Contains(id))
throw new NotSupportedException($"{id} is not distinct!");
distinct.Add(id);
results.Add($" {id}(fa:{host.Type}{newLine}{host.Colon}{newLine}{host.Hyphen}{newLine}{host.Device}{newLine}https://{host.Name}/)");
}
results.Add(" end");
results.Add($" subgraph {title}");
foreach (Host host in from l in hosts orderby l.Location, l.Type, l.Line select l)
{
if (host.Id is null || host.Hyphen is null || host.Device is null || host.Name is null || host.Hyphen.Length != 17)
continue;
if (!int.TryParse(host.Id, out id))
throw new NotSupportedException($"{host.Id} is not a number");
check = host.Type == wired ? "-->" : "-.->";
results.Add($" {id} {check} |{id}| {host.Location}{host.Type}{host.Line}");
}
results.Add(" end");
results.Add($" subgraph {title}");
foreach (Host host in from l in hosts orderby l.Line, l.Location, l.Type select l)
{
if (host.Id is null || host.Hyphen is null || host.Device is null || host.Name is null || host.Line is null || host.Hyphen.Length != 17)
continue;
if (!int.TryParse(host.Id, out id))
throw new NotSupportedException($"{host.Id} is not a number");
check = host.Type == wired ? "-->" : "-.->";
results.Add($" {host.Location}{host.Type}{host.Line} {check} Line{host.Line}");
}
results.Add(" end");
results.Add("```");
return results.AsReadOnly();
}
internal static void JsonToMarkdown(ILogger<Worker> logger, List<string> args)
{
Host[] hosts;
string title = args[3];
string wired = args[4];
string extension = args[5];
string searchPattern = args[2];
ReadOnlyCollection<string> lines;
string sourceDirectory = Path.GetFullPath(args[0]);
string[] files = Directory.GetFiles(sourceDirectory, searchPattern, SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
hosts = GetHosts(logger, file);
lines = GetLines(hosts, title, wired);
File.WriteAllText($"{file}{extension}", string.Join(Environment.NewLine, lines));
}
}
}

View File

@ -0,0 +1,206 @@
using File_Folder_Helper.Models;
using Microsoft.Extensions.Logging;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
namespace File_Folder_Helper.Day;
internal static partial class Helper20240724
{
private record FileConnectorConfigurationSystem(string AlternateTargetFolder,
string FileAgeThreshold,
string[] SourceFileFilters,
string TargetFileLocation);
#pragma warning disable IDE0028, IDE0056, IDE0300, IDE0240, IDE0241
private static readonly HttpClient _HttpClient = new();
private static readonly string _StaticFileServer = "localhost:5054";
private static readonly FileConnectorConfigurationSystem _FileConnectorConfiguration = new(
"D:/Tmp/Phares/AlternateTargetFolder",
"000:20:00:01",
[".txt"],
"D:/Tmp/Phares/TargetFileLocation");
private static DateTime GetFileAgeThresholdDateTime(string fileAgeThreshold)
{
DateTime result = DateTime.Now;
string[] segments = fileAgeThreshold.Split(':');
for (int i = 0; i < segments.Length; i++)
{
result = i switch
{
0 => result.AddDays(double.Parse(segments[i]) * -1),
1 => result.AddHours(double.Parse(segments[i]) * -1),
2 => result.AddMinutes(double.Parse(segments[i]) * -1),
3 => result.AddSeconds(double.Parse(segments[i]) * -1),
_ => throw new Exception(),
};
}
return result;
}
private static string[] GetValidWeeks(DateTime fileAgeThresholdDateTime)
{
DateTime dateTime = DateTime.Now;
Calendar calendar = new CultureInfo("en-US").Calendar;
string weekOfYear = $"{dateTime:yyyy}_Week_{calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday):00}";
string lastWeekOfYear = $"{fileAgeThresholdDateTime:yyyy}_Week_{calendar.GetWeekOfYear(fileAgeThresholdDateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday):00}";
return new string[] { weekOfYear, lastWeekOfYear }.Distinct().ToArray();
}
private static string[] GetValidDays(DateTime fileAgeThresholdDateTime)
{
DateTime dateTime = DateTime.Now;
return new string[] { dateTime.ToString("yyyy-MM-dd"), fileAgeThresholdDateTime.ToString("yyyy-MM-dd") }.Distinct().ToArray();
}
private static ReadOnlyCollection<NginxFileSystem> GetDayNginxFileSystemCollection(DateTime fileAgeThresholdDateTime, string week, string day, string dayUrl, NginxFileSystem[] dayNginxFileSystemCollection)
{
List<NginxFileSystem> results = new();
DateTime dateTime;
string nginxFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
foreach (NginxFileSystem dayNginxFileSystem in dayNginxFileSystemCollection)
{
if (!DateTime.TryParseExact(dayNginxFileSystem.MTime.Replace("GMT", "+00:00"), nginxFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
continue;
if (dateTime < fileAgeThresholdDateTime)
continue;
results.Add(new(
Path.GetFullPath(Path.Combine(_FileConnectorConfiguration.TargetFileLocation, week, day, dayNginxFileSystem.Name)),
string.Concat(dayUrl, '/', dayNginxFileSystem.Name),
dateTime.ToString(),
dayNginxFileSystem.Size));
}
return results.AsReadOnly();
}
private static ReadOnlyCollection<NginxFileSystem> GetDayNginxFileSystemCollection(DateTime fileAgeThresholdDateTime)
{
#nullable enable
List<NginxFileSystem> results = new();
string dayUrl;
string dayJson;
string weekJson;
string checkWeek;
Task<HttpResponseMessage> task;
NginxFileSystem[]? dayNginxFileSystemCollection;
NginxFileSystem[]? weekNginxFileSystemCollection;
string[] days = GetValidDays(fileAgeThresholdDateTime);
string[] weeks = GetValidWeeks(fileAgeThresholdDateTime);
foreach (string week in weeks)
{
checkWeek = string.Concat("http://", _StaticFileServer, '/', week);
task = _HttpClient.GetAsync(checkWeek);
task.Wait();
if (!task.Result.IsSuccessStatusCode)
continue;
weekJson = _HttpClient.GetStringAsync(checkWeek).Result;
weekNginxFileSystemCollection = JsonSerializer.Deserialize(weekJson, NginxFileSystemCollectionSourceGenerationContext.Default.NginxFileSystemArray);
if (weekNginxFileSystemCollection is null)
continue;
foreach (NginxFileSystem weekNginxFileSystem in weekNginxFileSystemCollection)
{
if (!(from l in days where weekNginxFileSystem.Name == l select false).Any())
continue;
dayUrl = string.Concat(checkWeek, '/', weekNginxFileSystem.Name);
dayJson = _HttpClient.GetStringAsync(dayUrl).Result;
dayNginxFileSystemCollection = JsonSerializer.Deserialize(dayJson, NginxFileSystemCollectionSourceGenerationContext.Default.NginxFileSystemArray);
if (dayNginxFileSystemCollection is null)
continue;
results.AddRange(GetDayNginxFileSystemCollection(fileAgeThresholdDateTime, week, weekNginxFileSystem.Name, dayUrl, dayNginxFileSystemCollection));
}
}
return results.AsReadOnly();
#nullable disable
}
private static ReadOnlyCollection<Tuple<DateTime, FileInfo, FileInfo, string>> GetPossible()
{
List<Tuple<DateTime, FileInfo, FileInfo, string>> results = new();
DateTime dateTime;
FileInfo targetFileInfo;
FileInfo alternateFileInfo;
DateTime fileAgeThresholdDateTime = GetFileAgeThresholdDateTime(_FileConnectorConfiguration.FileAgeThreshold);
ReadOnlyCollection<NginxFileSystem> dayNginxFileSystemCollection = GetDayNginxFileSystemCollection(fileAgeThresholdDateTime);
foreach (NginxFileSystem nginxFileSystem in dayNginxFileSystemCollection)
{
targetFileInfo = new FileInfo(nginxFileSystem.Name);
if (targetFileInfo.Directory is null)
continue;
if (!Directory.Exists(targetFileInfo.Directory.FullName))
_ = Directory.CreateDirectory(targetFileInfo.Directory.FullName);
if (!DateTime.TryParse(nginxFileSystem.MTime, out dateTime))
continue;
if (targetFileInfo.Exists && targetFileInfo.LastWriteTime == dateTime)
continue;
alternateFileInfo = new(Path.Combine(_FileConnectorConfiguration.AlternateTargetFolder, nginxFileSystem.Name));
results.Add(new(dateTime, targetFileInfo, alternateFileInfo, nginxFileSystem.Type));
}
return (from l in results orderby l.Item1 select l).ToList().AsReadOnly();
}
private static void Test()
{
#nullable enable
if (_HttpClient is null)
throw new Exception();
if (string.IsNullOrEmpty(_StaticFileServer))
throw new Exception();
if (string.IsNullOrEmpty(_StaticFileServer))
{
ReadOnlyCollection<Tuple<DateTime, FileInfo, FileInfo, string>> possibleDownload = GetPossible();
if (possibleDownload.Count > 0)
{
string targetFileName = possibleDownload[0].Item4;
FileInfo targetFileInfo = possibleDownload[0].Item2;
FileInfo alternateFileInfo = possibleDownload[0].Item3;
DateTime matchNginxFileSystemDateTime = possibleDownload[0].Item1;
// if (alternateFileInfo.Exists)
// File.Delete(alternateFileInfo.FullName);
if (targetFileInfo.Exists)
File.Delete(targetFileInfo.FullName);
string targetJson = _HttpClient.GetStringAsync(targetFileName).Result;
File.WriteAllText(targetFileInfo.FullName, targetJson);
targetFileInfo.LastWriteTime = matchNginxFileSystemDateTime;
// File.Copy(targetFileInfo.FullName, alternateFileInfo.FullName);
File.AppendAllText(alternateFileInfo.FullName, targetJson);
}
}
#nullable disable
}
internal static void CopyDirectories(ILogger<Worker> logger, List<string> args)
{
Test();
string[] files;
Process process;
string checkDirectory;
string filter = args[3];
string replaceWith = args[4];
string searchPattern = args[2];
string sourceDirectory = Path.GetFullPath(args[0]);
string[] foundDirectories = Directory.GetDirectories(sourceDirectory, searchPattern, SearchOption.AllDirectories);
logger.LogInformation($"Found {foundDirectories.Length} directories");
foreach (string foundDirectory in foundDirectories)
{
if (!foundDirectory.Contains(filter))
continue;
logger.LogDebug(foundDirectory);
checkDirectory = foundDirectory.Replace(filter, replaceWith);
if (Directory.Exists(checkDirectory))
{
files = Directory.GetFiles(checkDirectory, "*", SearchOption.AllDirectories);
if (files.Length > 0)
continue;
Directory.Delete(checkDirectory);
}
process = Process.Start("cmd.exe", $"/c xCopy \"{foundDirectory}\" \"{checkDirectory}\" /S /E /I /H /Y");
process.WaitForExit();
}
}
}

View File

@ -0,0 +1,64 @@
using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace File_Folder_Helper.Day;
internal static partial class Helper20240728
{
internal static void DownloadSslCertificates(ILogger<Worker> logger, List<string> args)
{
string file;
Process? process;
string[] segments;
string standardError;
string standardOutput;
string argumentSegment;
string store = args[9];
string domain = args[2];
List<string> lines = [];
string logSegment = args[8];
string endCertificate = args[7];
string beginCertificate = args[6];
int waitForExit = int.Parse(args[5]);
string[] subdomains = args[3].Split(',');
string sourceDirectory = Path.GetFullPath(args[0]);
ProcessStartInfo processStartInfo = new()
{
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
FileName = args[4],
WorkingDirectory = sourceDirectory
};
foreach (string subdomain in subdomains)
{
argumentSegment = $"{subdomain}.{domain}:443 -servername {subdomain}.{domain}";
processStartInfo.Arguments = $"s_client -connect {subdomain}.{domain}:443 -servername {subdomain}.{domain}";
process = Process.Start(processStartInfo);
if (process is null)
continue;
_ = process.WaitForExit(waitForExit);
process.Kill(entireProcessTree: true);
standardOutput = process.StandardOutput.ReadToEnd();
if (!standardOutput.Contains(beginCertificate) || !standardOutput.Contains(endCertificate))
{
standardError = process.StandardError.ReadToEnd();
logger.LogWarning($"Error: {subdomain}{Environment.NewLine}{standardOutput}{Environment.NewLine}{standardError}");
continue;
}
segments = standardOutput.Split(beginCertificate);
if (segments.Length != 2)
break;
segments = segments[1].Split(endCertificate);
if (segments.Length != 2)
break;
lines.Add($"{logSegment} \"{store}\" {subdomain}.{domain}.cert");
file = Path.Combine(sourceDirectory, $"{subdomain}.{domain}.cert");
File.WriteAllText(file, $"{beginCertificate}{segments[0]}{endCertificate}{Environment.NewLine}");
}
File.WriteAllLines(Path.Combine(sourceDirectory, $"{DateTime.Now.Ticks}.txt"), lines);
}
}

View File

@ -76,7 +76,15 @@ internal static class HelperDay
else if (args[1] == "Day-Helper-2024-06-23") else if (args[1] == "Day-Helper-2024-06-23")
Day.Helper20240623.UpdateSubTasksInMarkdownFiles(logger, args); Day.Helper20240623.UpdateSubTasksInMarkdownFiles(logger, args);
else if (args[1] == "Day-Helper-2024-06-24") else if (args[1] == "Day-Helper-2024-06-24")
Day.Helper20240624.MoveUpOndDirectory(logger, args); Day.Helper20240624.MoveUpOneDirectory(logger, args);
else if (args[1] == "Day-Helper-2024-07-11")
Day.Helper20240711.GitRemoteRemove(logger, args);
else if (args[1] == "Day-Helper-2024-07-18")
Day.Helper20240718.JsonToMarkdown(logger, args);
else if (args[1] == "Day-Helper-2024-07-24")
Day.Helper20240724.CopyDirectories(logger, args);
else if (args[1] == "Day-Helper-2024-07-28")
Day.Helper20240728.DownloadSslCertificates(logger, args);
else else
throw new Exception(appSettings.Company); throw new Exception(appSettings.Company);
} }

View File

@ -16,10 +16,10 @@
<PackageReference Include="DiscUtils.Iso9660" Version="0.16.13" /> <PackageReference Include="DiscUtils.Iso9660" Version="0.16.13" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="runtime.win-x64.Microsoft.DotNet.ILCompiler" Version="8.0.6" /> <PackageReference Include="runtime.win-x64.Microsoft.DotNet.ILCompiler" Version="8.0.7" />
<PackageReference Include="System.Text.Json" Version="8.0.3" /> <PackageReference Include="System.Text.Json" Version="8.0.4" />
<PackageReference Include="TextCopy" Version="6.2.1" /> <PackageReference Include="TextCopy" Version="6.2.1" />
<PackageReference Include="WindowsShortcutFactory" Version="1.2.0" /> <PackageReference Include="WindowsShortcutFactory" Version="1.2.0" />
<PackageReference Include="YamlDotNet" Version="15.3.0" /> <PackageReference Include="YamlDotNet" Version="16.0.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -43,24 +43,78 @@ internal static class HelperGit
return result.Output; return result.Output;
} }
private static List<string> GetOthersModifiedAndDeletedExcludingStandardFilesAsList(string repositoryDirectory, bool usePathCombine, CancellationToken cancellationToken)
{
List<string> results = [];
Task<string> task = RunAsync("ls-files --others --modified --deleted --exclude-standard", repositoryDirectory, cancellationToken);
task.Wait(cancellationToken);
string[] files = task.Result.Split("\r\n");
foreach (string file in files)
{
if (!usePathCombine)
results.Add(file);
else
results.Add(Path.GetFullPath(Path.Combine(repositoryDirectory, file)));
}
return results;
}
internal static ReadOnlyCollection<string> GetOthersModifiedAndDeletedExcludingStandardFiles(string repositoryDirectory, bool usePathCombine, CancellationToken cancellationToken) internal static ReadOnlyCollection<string> GetOthersModifiedAndDeletedExcludingStandardFiles(string repositoryDirectory, bool usePathCombine, CancellationToken cancellationToken)
{ {
List<string> results = []; List<string> results = [];
List<string> relativePathFiles;
DirectoryInfo directoryInfo;
bool usePathCombineInner = false;
string checkDirectory = Path.Combine(repositoryDirectory, ".git"); string checkDirectory = Path.Combine(repositoryDirectory, ".git");
if (Directory.Exists(checkDirectory)) if (Directory.Exists(checkDirectory))
results.AddRange(GetOthersModifiedAndDeletedExcludingStandardFilesAsList(repositoryDirectory, usePathCombine, cancellationToken));
string[] subdirectories = Directory.GetDirectories(repositoryDirectory, "*", SearchOption.TopDirectoryOnly);
foreach (string subdirectory in subdirectories)
{ {
Task<string> task = RunAsync($"ls-files --others --modified --deleted --exclude-standard", repositoryDirectory, cancellationToken); directoryInfo = new(subdirectory);
task.Wait(cancellationToken); if (directoryInfo.LinkTarget is null)
string[] files = task.Result.Split("\r\n"); continue;
foreach (string file in files) checkDirectory = Path.Combine(directoryInfo.LinkTarget, ".git");
{ if (!Directory.Exists(checkDirectory))
if (!usePathCombine) continue;
results.Add(file); relativePathFiles = GetOthersModifiedAndDeletedExcludingStandardFilesAsList(directoryInfo.LinkTarget, usePathCombineInner, cancellationToken);
else foreach (string relativePathFile in relativePathFiles)
results.Add(Path.GetFullPath(Path.Combine(repositoryDirectory, file))); results.Add(Path.GetFullPath(Path.Combine(subdirectory, relativePathFile)));
}
} }
return new(results); return new(results);
} }
internal static ReadOnlyCollection<string> RemoteRemove(string repositoryDirectory, string name, CancellationToken cancellationToken)
{
List<string> results = [];
Task<string> task = RunAsync($"remote rm {name}", repositoryDirectory, cancellationToken);
task.Wait(cancellationToken);
string[] lines = task.Result.Split("\r\n");
foreach (string line in lines)
results.Add(line);
return new(results);
}
internal static ReadOnlyCollection<string> RemoteAdd(string repositoryDirectory, string name, string url, CancellationToken cancellationToken)
{
List<string> results = [];
Task<string> task = RunAsync($"remote add {name} {url}", repositoryDirectory, cancellationToken);
task.Wait(cancellationToken);
string[] lines = task.Result.Split("\r\n");
foreach (string line in lines)
results.Add(line);
return new(results);
}
internal static ReadOnlyCollection<string> PushBranch(string repositoryDirectory, string remote, string name, CancellationToken cancellationToken)
{
List<string> results = [];
Task<string> task = RunAsync($"push {remote} {name}", repositoryDirectory, cancellationToken);
task.Wait(cancellationToken);
string[] lines = task.Result.Split("\r\n");
foreach (string line in lines)
results.Add(line);
return new(results);
}
} }

View File

@ -160,7 +160,7 @@ internal static partial class HelperKanbanMetadata
results.Add(lines[i]); results.Add(lines[i]);
} }
} }
results.Add($"status: \"{record.GroupCount}-{record.Group}\""); results.Add($"status: {record.GroupCount}-{record.Group}");
results.Add("```"); results.Add("```");
results.Add(string.Empty); results.Add(string.Empty);
} }
@ -201,7 +201,7 @@ internal static partial class HelperKanbanMetadata
(lines, lineNumber) = HelperMarkdown.GetStatusAndFrontMatterYamlEndLineNumbers(record.FileInfo); (lines, lineNumber) = HelperMarkdown.GetStatusAndFrontMatterYamlEndLineNumbers(record.FileInfo);
if (lines.Count == 0) if (lines.Count == 0)
continue; continue;
statusLine = $"status: \"{record.GroupCount}-{record.Group}\""; statusLine = $"status: {record.GroupCount}-{record.Group}";
paramCase = lineNumber.H1 is null ? null : GetParamCase(lines[lineNumber.H1.Value]); paramCase = lineNumber.H1 is null ? null : GetParamCase(lines[lineNumber.H1.Value]);
match = lineNumber.H1 is null || paramCase is null ? null : Path.GetFileNameWithoutExtension(record.FileInfo.Name) == paramCase; match = lineNumber.H1 is null || paramCase is null ? null : Path.GetFileNameWithoutExtension(record.FileInfo.Name) == paramCase;
if (lineNumber.FrontMatterYamlEnd is null) if (lineNumber.FrontMatterYamlEnd is null)

File diff suppressed because it is too large Load Diff

20
Models/Host.cs Normal file
View File

@ -0,0 +1,20 @@
using System.Text.Json.Serialization;
namespace File_Folder_Helper.Models;
public record Host([property: JsonPropertyName("a")] string? Id,
[property: JsonPropertyName("b")] string? Colon,
[property: JsonPropertyName("c")] string? Hyphen,
[property: JsonPropertyName("d")] string? Line,
[property: JsonPropertyName("e")] string? Count,
[property: JsonPropertyName("f")] string? Segments,
[property: JsonPropertyName("g")] string? Type,
[property: JsonPropertyName("h")] string? Device,
[property: JsonPropertyName("i")] string? Name,
[property: JsonPropertyName("j")] string? Location);
[JsonSourceGenerationOptions(WriteIndented = true, AllowTrailingCommas = true)]
[JsonSerializable(typeof(Host[]))]
public partial class HostSourceGenerationContext : JsonSerializerContext
{
}

30
Models/NginxFileSystem.cs Normal file
View File

@ -0,0 +1,30 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Folder_Helper.Models;
public record NginxFileSystem(string Name,
string Type,
string MTime,
float Size)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, NginxFileSystemSourceGenerationContext.Default.NginxFileSystem);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(NginxFileSystem))]
internal partial class NginxFileSystemSourceGenerationContext : JsonSerializerContext
{
}
[JsonSourceGenerationOptions(WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(NginxFileSystem[]))]
internal partial class NginxFileSystemCollectionSourceGenerationContext : JsonSerializerContext
{
}

43
Models/VSCodeTasks.cs Normal file
View File

@ -0,0 +1,43 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace File_Folder_Helper.Models;
public record VSCodeTask([property: JsonPropertyName("label")] string? Label,
[property: JsonPropertyName("command")] string? Command,
[property: JsonPropertyName("type")] string? Type,
[property: JsonPropertyName("args")] IReadOnlyList<string>? Arguments,
[property: JsonPropertyName("script")] string? Script)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, VSCodeTaskSourceGenerationContext.Default.VSCodeTask);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true, PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(VSCodeTask))]
internal partial class VSCodeTaskSourceGenerationContext : JsonSerializerContext
{
}
public record VSCodeTasks([property: JsonPropertyName("version")] string? Version,
[property: JsonPropertyName("tasks")] VSCodeTask[]? TaskCollection)
{
public override string ToString()
{
string result = JsonSerializer.Serialize(this, VSCodeTasksSourceGenerationContext.Default.VSCodeTasks);
return result;
}
}
[JsonSourceGenerationOptions(WriteIndented = true, PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(VSCodeTasks))]
internal partial class VSCodeTasksSourceGenerationContext : JsonSerializerContext
{
}

View File

@ -12,7 +12,7 @@ internal class Program
public static void Main(string[] args) public static void Main(string[] args)
{ {
#pragma warning disable IL3050 #pragma warning disable IL3050
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args); HostApplicationBuilder builder = Microsoft.Extensions.Hosting.Host.CreateApplicationBuilder(args);
#pragma warning restore IL3050 #pragma warning restore IL3050
_ = builder.Configuration.AddEnvironmentVariables(); _ = builder.Configuration.AddEnvironmentVariables();
_ = builder.Configuration.AddUserSecrets<Program>(); _ = builder.Configuration.AddUserSecrets<Program>();