YamlDotNet sort yaml
Helper20240623 Sorted Improved log Force root directory modified date when updating file Switched to bash over link MoveUpOneDirectory Only write if needed UpdateSubTasksInMarkdownFiles
This commit is contained in:
parent
47e6b85c21
commit
1cd20fa08b
9
.vscode/mklink.md
vendored
9
.vscode/mklink.md
vendored
@ -15,7 +15,10 @@ mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.kanbn" "D:\5-Other-Small\Kanban
|
||||
```
|
||||
|
||||
```bash
|
||||
mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode" "C:\Users\phares\.vscode\extensions\ifx.type-script-helper-1.6.1"
|
||||
mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-oss" "C:\Users\phares\.vscode-oss\extensions\ifx.type-script-helper-1.6.1"
|
||||
mklink /J "L:\DevOps\Mesa_FI\File-Folder-Helper\.extensions-vscode-insiders" "C:\Users\phares\.vscode-insiders\extensions\ifx.type-script-helper-1.6.1"
|
||||
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-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-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-insiders" "C:\Users\phares\.vscode-insiders\extensions\ifx.type-script-helper-1.6.2"
|
||||
```
|
||||
|
@ -133,7 +133,7 @@ internal static partial class Helper20240106
|
||||
return results;
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<string> GetIpAddressAndVerify(ILogger<Worker> logger, string key, Dictionary<string, Dictionary<string, string>> keyValuePairs, Dictionary<int, Host> hosts)
|
||||
private static ReadOnlyCollection<string> GetIpAddressAndVerify(ILogger<Worker> logger, string key, Dictionary<string, Dictionary<string, string>> keyValuePairs, Dictionary<int, Host> hosts, string filter)
|
||||
{
|
||||
List<string> results = [];
|
||||
int id;
|
||||
@ -145,6 +145,8 @@ internal static partial class Helper20240106
|
||||
foreach (KeyValuePair<string, Dictionary<string, string>> keyValuePair in keyValuePairs)
|
||||
{
|
||||
found = false;
|
||||
if (keyValuePair.Key.StartsWith(filter))
|
||||
continue;
|
||||
if (!keyValuePair.Value.TryGetValue(key, out ipAddress))
|
||||
throw new NotSupportedException($"{key} isn't present!");
|
||||
if (ipAddress == "0.0.0.0")
|
||||
@ -208,6 +210,7 @@ internal static partial class Helper20240106
|
||||
int? headerLine;
|
||||
FileInfo fileInfo;
|
||||
string key = args[7];
|
||||
string filter = args[10];
|
||||
string replace = args[5];
|
||||
int keyIndex = int.Parse(args[3]);
|
||||
int keyLength = int.Parse(args[4]);
|
||||
@ -234,7 +237,7 @@ internal static partial class Helper20240106
|
||||
keyValuePairs = GetKeyValuePairs(keyIndex, keyLength, replace, headers, lines, headerLine.Value);
|
||||
if (keyValuePairs.Count == 0)
|
||||
continue;
|
||||
ipAddress = GetIpAddressAndVerify(logger, key, keyValuePairs, hosts);
|
||||
ipAddress = GetIpAddressAndVerify(logger, key, keyValuePairs, hosts, filter);
|
||||
if (ipAddress.Count == 0)
|
||||
continue;
|
||||
json = JsonSerializer.Serialize(keyValuePairs, DictionaryDictionarySourceGenerationContext.Default.DictionaryStringDictionaryStringString);
|
||||
|
156
Day/2024-Q2/Helper-2024-06-23.cs
Normal file
156
Day/2024-Q2/Helper-2024-06-23.cs
Normal file
@ -0,0 +1,156 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace File_Folder_Helper.Day;
|
||||
|
||||
internal static partial class Helper20240623
|
||||
{
|
||||
|
||||
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)
|
||||
{
|
||||
List<Record> results = [];
|
||||
int? stopLine;
|
||||
int? subTasksLine;
|
||||
int? codeInsidersLine;
|
||||
string[] lines;
|
||||
string[] files = Directory.GetFiles(sourceDirectory, searchPattern, SearchOption.AllDirectories);
|
||||
foreach (string file in files)
|
||||
{
|
||||
stopLine = null;
|
||||
subTasksLine = null;
|
||||
codeInsidersLine = null;
|
||||
lines = File.ReadAllLines(file);
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (lines[i].StartsWith(codeInsiders) && lines[i][^1] == '"')
|
||||
{
|
||||
if (lines.Length > i + 1 && lines[i + 1] == "```")
|
||||
codeInsidersLine = i;
|
||||
}
|
||||
if (lines[i] != subTasks)
|
||||
continue;
|
||||
subTasksLine = i;
|
||||
if (codeInsidersLine is null)
|
||||
break;
|
||||
if (lines.Length > i)
|
||||
{
|
||||
for (int j = i + 1; j < lines.Length; j++)
|
||||
{
|
||||
if (lines[j].Length > 0 && lines[j][0] == '#')
|
||||
{
|
||||
stopLine = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
stopLine ??= lines.Length;
|
||||
break;
|
||||
}
|
||||
results.Add(new(codeInsidersLine, file, lines, stopLine, subTasksLine));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
internal static void UpdateSubTasksInMarkdownFiles(ILogger<Worker> logger, List<string> args)
|
||||
{
|
||||
int lineCheck;
|
||||
bool? foundDone;
|
||||
string[] segments;
|
||||
List<string> lines;
|
||||
string[] indexLines;
|
||||
string checkDirectory;
|
||||
string done = args[7];
|
||||
List<string> indexFiles;
|
||||
string subTasks = args[3];
|
||||
List<string> newLines = [];
|
||||
List<string> oldLines = [];
|
||||
string indexFile = args[5];
|
||||
string searchPattern = args[2];
|
||||
string directoryFilter = args[8];
|
||||
string[] tasks = args[6].Split(',');
|
||||
string codeInsiders = $"{args[4]} \"";
|
||||
string sourceDirectory = Path.GetFullPath(args[0]);
|
||||
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)
|
||||
{
|
||||
if (record.SubTasksLine is null)
|
||||
continue;
|
||||
if (record.CodeInsidersLine is not null)
|
||||
logger.LogInformation("<{file}> has [{subTasks}]", Path.GetFileNameWithoutExtension(record.File), subTasks);
|
||||
else
|
||||
{
|
||||
logger.LogWarning("<{file}> has [{subTasks}] but doesn't have [{codeInsiders}]!", Path.GetFileNameWithoutExtension(record.File), subTasks, codeInsiders);
|
||||
continue;
|
||||
}
|
||||
if (record.StopLine is null)
|
||||
continue;
|
||||
checkDirectory = record.Lines[record.CodeInsidersLine.Value][codeInsiders.Length..^1];
|
||||
if (!Directory.Exists(checkDirectory))
|
||||
{
|
||||
logger.LogError("<{checkDirectory}> doesn't exist", Path.GetFileName(checkDirectory));
|
||||
continue;
|
||||
}
|
||||
indexFiles = Directory.GetFiles(checkDirectory, indexFile, SearchOption.AllDirectories).ToList();
|
||||
if (indexFiles.Count != 1)
|
||||
{
|
||||
for (int i = indexFiles.Count - 1; i > -1; i--)
|
||||
{
|
||||
if (!indexFiles[i].Contains(directoryFilter, StringComparison.CurrentCultureIgnoreCase))
|
||||
indexFiles.RemoveAt(i);
|
||||
}
|
||||
if (indexFiles.Count != 1)
|
||||
{
|
||||
logger.LogError("<{checkDirectory}> doesn't have a [{indexFile}]", Path.GetFileName(checkDirectory), indexFile);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
foundDone = null;
|
||||
newLines.Clear();
|
||||
oldLines.Clear();
|
||||
indexLines = File.ReadAllLines(indexFiles[0]);
|
||||
for (int i = 0; i < indexLines.Length; i++)
|
||||
{
|
||||
if (indexLines[i] == done)
|
||||
foundDone = true;
|
||||
segments = indexLines[i].Split(tasks[1]);
|
||||
if (segments.Length > 2 || !segments[0].StartsWith(tasks[0]))
|
||||
continue;
|
||||
if (foundDone is null || !foundDone.Value)
|
||||
newLines.Add($"- [ ] {segments[0][tasks[0].Length..]}");
|
||||
else
|
||||
newLines.Add($"- [x] {segments[0][tasks[0].Length..]}");
|
||||
}
|
||||
if (newLines.Count == 0)
|
||||
continue;
|
||||
lineCheck = 0;
|
||||
newLines.Insert(0, string.Empty);
|
||||
for (int i = record.SubTasksLine.Value + 1; i < record.StopLine.Value - 1; i++)
|
||||
oldLines.Add(record.Lines[i]);
|
||||
if (newLines.Count == oldLines.Count)
|
||||
{
|
||||
for (int i = 0; i < newLines.Count; i++)
|
||||
{
|
||||
if (newLines[i] != record.Lines[record.SubTasksLine.Value + 1 + i])
|
||||
continue;
|
||||
lineCheck++;
|
||||
}
|
||||
if (lineCheck == newLines.Count)
|
||||
continue;
|
||||
}
|
||||
checkDirectory = Path.Combine(checkDirectory, DateTime.Now.Ticks.ToString());
|
||||
_ = Directory.CreateDirectory(checkDirectory);
|
||||
Thread.Sleep(500);
|
||||
Directory.Delete(checkDirectory);
|
||||
lines = record.Lines.ToList();
|
||||
for (int i = record.StopLine.Value - 1; i > record.SubTasksLine.Value + 1; i--)
|
||||
lines.RemoveAt(i);
|
||||
if (record.StopLine.Value == record.Lines.Length && lines[^1].Length == 0)
|
||||
lines.RemoveAt(lines.Count - 1);
|
||||
for (int i = 0; i < newLines.Count; i++)
|
||||
lines.Insert(record.SubTasksLine.Value + 1 + i, newLines[i]);
|
||||
File.WriteAllLines(record.File, lines);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
88
Day/2024-Q2/Helper-2024-06-24.cs
Normal file
88
Day/2024-Q2/Helper-2024-06-24.cs
Normal file
@ -0,0 +1,88 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace File_Folder_Helper.Day;
|
||||
|
||||
internal static partial class Helper20240624
|
||||
{
|
||||
|
||||
private static void MoveUpOndDirectory(ILogger<Worker> logger, string sourceDirectory, string[] files)
|
||||
{
|
||||
string? match;
|
||||
string checkFile;
|
||||
FileInfo fileInfoA;
|
||||
FileInfo fileInfoB;
|
||||
string? checkDirectory;
|
||||
List<string> deleteFiles = [];
|
||||
Dictionary<string, string> keyValuePairs = [];
|
||||
foreach (string file in files)
|
||||
{
|
||||
checkDirectory = Path.GetDirectoryName(Path.GetDirectoryName(file)) ?? throw new NotSupportedException();
|
||||
checkFile = Path.Combine(checkDirectory, Path.GetFileName(file));
|
||||
if (File.Exists(checkFile))
|
||||
throw new NotSupportedException();
|
||||
if (keyValuePairs.TryGetValue(checkFile, out match))
|
||||
{
|
||||
fileInfoA = new(file);
|
||||
fileInfoB = new(match);
|
||||
if (fileInfoA.Length != fileInfoB.Length)
|
||||
throw new NotSupportedException("Files don't match!");
|
||||
logger.LogWarning("<{file}> already exists!", file);
|
||||
deleteFiles.Add(file);
|
||||
continue;
|
||||
}
|
||||
keyValuePairs.Add(checkFile, file);
|
||||
}
|
||||
foreach (string file in deleteFiles)
|
||||
File.Delete(file);
|
||||
foreach (KeyValuePair<string, string> keyValuePair in keyValuePairs)
|
||||
File.Move(keyValuePair.Value, keyValuePair.Key);
|
||||
Helpers.HelperDeleteEmptyDirectories.DeleteEmptyDirectories(logger, sourceDirectory);
|
||||
}
|
||||
|
||||
private static void Distinct(List<string> args, string sourceDirectory, string[] deleteMatchingIdsDirectoryNames, string[] files)
|
||||
{
|
||||
string fileName;
|
||||
string directory;
|
||||
List<string> distinct = [];
|
||||
List<string> duplicate = [];
|
||||
string[] keepMatchingIdsDirectoryNames = args[4].Split(',');
|
||||
if (deleteMatchingIdsDirectoryNames.Length != keepMatchingIdsDirectoryNames.Length)
|
||||
throw new NotSupportedException("Check arg lengths!");
|
||||
string[] keepMatchingIdsDirectories = keepMatchingIdsDirectoryNames.Select(l => Path.Combine(sourceDirectory, l)).ToArray();
|
||||
string[] deleteMatchingIdsDirectories = deleteMatchingIdsDirectoryNames.Select(l => Path.Combine(sourceDirectory, l)).ToArray();
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileName = Path.GetFileName(file);
|
||||
if (distinct.Contains(fileName))
|
||||
{
|
||||
duplicate.Add(fileName);
|
||||
continue;
|
||||
}
|
||||
distinct.Add(Path.GetFileName(file));
|
||||
}
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileName = Path.GetFileName(file);
|
||||
directory = Path.GetDirectoryName(file) ?? throw new NotSupportedException();
|
||||
if (!duplicate.Contains(fileName))
|
||||
continue;
|
||||
if (deleteMatchingIdsDirectories.Contains(directory))
|
||||
File.Move(file, $"{file}.del");
|
||||
else if (!keepMatchingIdsDirectories.Contains(directory))
|
||||
throw new NotSupportedException($"Missing <{Path.GetFileName(directory)}> as a directory for {fileName}");
|
||||
}
|
||||
}
|
||||
|
||||
internal static void MoveUpOndDirectory(ILogger<Worker> logger, List<string> args)
|
||||
{
|
||||
string searchPattern = args[2];
|
||||
string sourceDirectory = Path.GetFullPath(args[0]);
|
||||
string[] deleteMatchingIdsDirectoryNames = args[3].Split(',');
|
||||
string[] files = Directory.GetFiles(sourceDirectory, searchPattern, SearchOption.AllDirectories);
|
||||
if (deleteMatchingIdsDirectoryNames.Length == 0)
|
||||
MoveUpOndDirectory(logger, sourceDirectory, files);
|
||||
else
|
||||
Distinct(args, sourceDirectory, deleteMatchingIdsDirectoryNames, files);
|
||||
}
|
||||
|
||||
}
|
@ -8,6 +8,7 @@ internal static class HelperDay
|
||||
|
||||
internal static void Select(AppSettings appSettings, ILogger<Worker> logger, List<string> args, CancellationToken cancellationToken)
|
||||
{
|
||||
logger.LogInformation("X) Day Helpers,");
|
||||
if (args[1] == "Day-Helper-2023-09-06")
|
||||
Day.Helper20230906.SaveJson(logger, args[0]);
|
||||
else if (args[1] == "Day-Helper-2023-10-10")
|
||||
@ -72,6 +73,10 @@ internal static class HelperDay
|
||||
Day.Helper20240519.FindReplaceDirectoryName(logger, args);
|
||||
else if (args[1] == "Day-Helper-2024-05-20")
|
||||
Day.Helper20240520.IdentifierRename(logger, args);
|
||||
else if (args[1] == "Day-Helper-2024-06-23")
|
||||
Day.Helper20240623.UpdateSubTasksInMarkdownFiles(logger, args);
|
||||
else if (args[1] == "Day-Helper-2024-06-24")
|
||||
Day.Helper20240624.MoveUpOndDirectory(logger, args);
|
||||
else
|
||||
throw new Exception(appSettings.Company);
|
||||
}
|
||||
|
@ -20,5 +20,6 @@
|
||||
<PackageReference Include="System.Text.Json" Version="8.0.3" />
|
||||
<PackageReference Include="TextCopy" Version="6.2.1" />
|
||||
<PackageReference Include="WindowsShortcutFactory" Version="1.2.0" />
|
||||
<PackageReference Include="YamlDotNet" Version="15.3.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
@ -6,6 +6,7 @@ using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.RegularExpressions;
|
||||
using YamlDotNet.Serialization;
|
||||
|
||||
namespace File_Folder_Helper.Helpers;
|
||||
|
||||
@ -26,6 +27,7 @@ internal static partial class HelperMarkdown
|
||||
string File,
|
||||
string FileName,
|
||||
string FileNameWithoutExtension,
|
||||
ReadOnlyDictionary<string, object> FrontMatterYaml,
|
||||
string H1,
|
||||
bool IsKanbanIndex,
|
||||
bool IsKanbanMarkdown,
|
||||
@ -212,12 +214,12 @@ internal static partial class HelperMarkdown
|
||||
{
|
||||
string? result;
|
||||
List<string> results;
|
||||
Dictionary<string, JsonElement>? keyValuePairs;
|
||||
string jsonLinesLast = jsonLines[^1];
|
||||
jsonLines.RemoveAt(jsonLines.Count - 1);
|
||||
jsonLines.Add(jsonLinesLast[..^1]);
|
||||
jsonLines.Insert(0, "{");
|
||||
jsonLines.Add("}");
|
||||
Dictionary<string, JsonElement>? keyValuePairs;
|
||||
result = string.Join(Environment.NewLine, jsonLines);
|
||||
keyValuePairs = JsonSerializer.Deserialize(result, DictionaryStringAndJsonElementSourceGenerationContext.Default.DictionaryStringJsonElement);
|
||||
if (keyValuePairs is null)
|
||||
@ -403,79 +405,6 @@ internal static partial class HelperMarkdown
|
||||
return results;
|
||||
}
|
||||
|
||||
private static (string?, Dictionary<string, JsonElement>?, string[]) Get(int frontMatterYamlEnd, string[] lines)
|
||||
{
|
||||
string? result;
|
||||
List<string> results;
|
||||
Dictionary<string, JsonElement>? keyValuePairs;
|
||||
string[] segments;
|
||||
string[] segmentsB;
|
||||
string segmentsLast;
|
||||
string segmentsFirst;
|
||||
List<string> jsonLines = [];
|
||||
for (int i = 0; i < frontMatterYamlEnd; i++)
|
||||
{
|
||||
if (lines[i] == "---")
|
||||
continue;
|
||||
segments = lines[i].Split(": ");
|
||||
if (segments.Length != 2)
|
||||
{
|
||||
jsonLines.Clear();
|
||||
break;
|
||||
}
|
||||
segmentsLast = segments[^1].Trim();
|
||||
segmentsFirst = segments[0].Trim();
|
||||
if (string.IsNullOrEmpty(segmentsLast))
|
||||
continue;
|
||||
if (segmentsFirst[0] == '"' && segmentsFirst[^1] == '"')
|
||||
jsonLines.Add($"{segmentsFirst}: ");
|
||||
else if (segmentsFirst[0] == '\'' && segmentsFirst[^1] == '\'')
|
||||
jsonLines.Add($"\"{segmentsFirst[1..^1]}\": ");
|
||||
else
|
||||
jsonLines.Add($"\"{segmentsFirst}\": ");
|
||||
if (segmentsLast == "[]")
|
||||
jsonLines.RemoveAt(jsonLines.Count - 1);
|
||||
else if (segmentsLast.Length > 4 && segmentsLast[0] == '[' && segmentsLast[^1] == ']' && segmentsLast[1] == '"' && segmentsLast[^2] == '"')
|
||||
jsonLines.Add($"{segmentsLast},");
|
||||
else if (segmentsLast[0] == '"' && segmentsLast[^1] == '"')
|
||||
jsonLines.Add($"{segmentsLast},");
|
||||
else if (segmentsLast[0] == '"' && segmentsLast[^1] == '"')
|
||||
jsonLines.Add($"\"{segmentsLast[1..^1]}\"");
|
||||
else if (!segmentsLast.Contains('"') && !segmentsLast.Contains('\''))
|
||||
{
|
||||
if (segmentsLast is "true" or "false")
|
||||
jsonLines.Add($"{segmentsLast},");
|
||||
else if (DateTime.TryParse(segmentsLast, out DateTime dateTime))
|
||||
jsonLines.Add($"\"{segmentsLast}\",");
|
||||
else if (segmentsLast.All(char.IsNumber))
|
||||
jsonLines.Add($"{segmentsLast},");
|
||||
else
|
||||
{
|
||||
segmentsB = segmentsLast.Split('.');
|
||||
if (segmentsB.Length == 2 && segmentsB[0].Length < 7 && segmentsB[^1].Length < 7 && segmentsB[0].All(char.IsNumber) && segmentsB[^1].All(char.IsNumber))
|
||||
jsonLines.Add($"{segmentsLast},");
|
||||
else if (!segmentsLast.Contains('[') && !segmentsLast.Contains('{'))
|
||||
jsonLines.Add($"\"{segmentsLast}\",");
|
||||
else
|
||||
{
|
||||
jsonLines.Clear();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
jsonLines.Clear();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (jsonLines.Count > 0)
|
||||
(result, keyValuePairs, results) = Get(jsonLines);
|
||||
else
|
||||
(result, keyValuePairs, results) = (null, null, []);
|
||||
return (result, keyValuePairs, results.ToArray());
|
||||
}
|
||||
|
||||
private static ReadOnlyDictionary<string, List<MarkdownFileAndLines>> GetKeyValuePairs(ReadOnlyDictionary<string, MarkdownFileAndLines> relativeToCollection)
|
||||
{
|
||||
Dictionary<string, List<MarkdownFileAndLines>> results = [];
|
||||
@ -594,6 +523,32 @@ internal static partial class HelperMarkdown
|
||||
return results;
|
||||
}
|
||||
|
||||
private static ReadOnlyCollection<string> GetFromMatterYamlLines(List<string> lines, LineNumber lineNumber)
|
||||
{
|
||||
List<string> results = [];
|
||||
if (lineNumber.FrontMatterYamlEnd is not null && lines.Count >= lineNumber.FrontMatterYamlEnd.Value)
|
||||
{
|
||||
for (int i = 1; i < lineNumber.FrontMatterYamlEnd.Value; i++)
|
||||
results.Add(lines[i]);
|
||||
}
|
||||
return new(results);
|
||||
}
|
||||
|
||||
private static ReadOnlyDictionary<string, object> GetFromMatterYaml(List<string> lines, LineNumber lineNumber)
|
||||
{
|
||||
Dictionary<string, object> results = [];
|
||||
IDeserializer deserializer = new DeserializerBuilder().Build();
|
||||
ReadOnlyCollection<string> frontMatterYamlLines = GetFromMatterYamlLines(lines, lineNumber);
|
||||
string frontMatterYaml = string.Join(Environment.NewLine, frontMatterYamlLines);
|
||||
Dictionary<string, object>? keyValuePairs = deserializer.Deserialize<Dictionary<string, object>>(frontMatterYaml);
|
||||
if (keyValuePairs is not null)
|
||||
{
|
||||
foreach (string key in keyValuePairs.Keys.OrderBy(l => l))
|
||||
results.Add(key, keyValuePairs[key]);
|
||||
}
|
||||
return new(results);
|
||||
}
|
||||
|
||||
private static ReadOnlyDictionary<string, MarkdownFileAndLines> GetRelativeToCollection(AppSettings appSettings, Input input, string[] files, ReadOnlyCollection<string> gitOthersModifiedAndDeletedExcludingStandardFiles, bool force)
|
||||
{
|
||||
Dictionary<string, MarkdownFileAndLines> results = [];
|
||||
@ -608,6 +563,7 @@ internal static partial class HelperMarkdown
|
||||
LineNumber lineNumber;
|
||||
MarkdownFile markdownFile;
|
||||
string fileNameWithoutExtension;
|
||||
ReadOnlyDictionary<string, object> frontMatterYaml;
|
||||
foreach (string file in files)
|
||||
{ // cSpell:disable
|
||||
fileInfo = new(file);
|
||||
@ -617,6 +573,7 @@ internal static partial class HelperMarkdown
|
||||
(lines, lineNumber) = GetStatusAndFrontMatterYamlEndLineNumbers(fileInfo);
|
||||
fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.FullName);
|
||||
h1 = fileNameWithoutExtension.ToLower().Replace("%20", "-").Replace(' ', '-');
|
||||
frontMatterYaml = GetFromMatterYaml(lines, lineNumber);
|
||||
if (lines.Count > 0)
|
||||
(type, h1) = GetTypeAndH1(appSettings, h1, lines, lineNumber);
|
||||
else
|
||||
@ -636,6 +593,7 @@ internal static partial class HelperMarkdown
|
||||
file,
|
||||
fileInfo.Name,
|
||||
fileNameWithoutExtension,
|
||||
frontMatterYaml,
|
||||
h1,
|
||||
isKanbanIndex,
|
||||
isKanbanMarkdown,
|
||||
@ -844,55 +802,6 @@ internal static partial class HelperMarkdown
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int ConvertFrontMatterToJsonFriendly(ReadOnlyDictionary<string, MarkdownFileAndLines> relativeToCollection, ReadOnlyCollection<string> gitOthersModifiedAndDeletedExcludingStandardFiles)
|
||||
{
|
||||
int result = 0;
|
||||
List<string> results = [];
|
||||
bool write;
|
||||
bool gitCheck;
|
||||
string[] lines;
|
||||
MarkdownFile markdownFile;
|
||||
string[] frontMatterYamlLines;
|
||||
foreach (KeyValuePair<string, MarkdownFileAndLines> relativeTo in relativeToCollection)
|
||||
{
|
||||
if (relativeTo.Value.Lines.Length == 0)
|
||||
continue;
|
||||
results.Clear();
|
||||
lines = relativeTo.Value.Lines;
|
||||
markdownFile = relativeTo.Value.MarkdownFile;
|
||||
if (markdownFile.LineNumber.FrontMatterYamlEnd is null)
|
||||
continue;
|
||||
(_, _, frontMatterYamlLines) = Get(markdownFile.LineNumber.FrontMatterYamlEnd.Value, lines);
|
||||
if (frontMatterYamlLines.Length == 0)
|
||||
continue;
|
||||
results.Add("---");
|
||||
results.AddRange(frontMatterYamlLines);
|
||||
results.Add("---");
|
||||
for (int i = markdownFile.LineNumber.FrontMatterYamlEnd.Value + 1; i < lines.Length; i++)
|
||||
results.Add(lines[i]);
|
||||
if (results.Count == lines.Length)
|
||||
{
|
||||
write = false;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (results[i] == lines[i])
|
||||
continue;
|
||||
write = true;
|
||||
break;
|
||||
}
|
||||
if (!write)
|
||||
continue;
|
||||
}
|
||||
gitCheck = gitOthersModifiedAndDeletedExcludingStandardFiles.Contains(markdownFile.File);
|
||||
if (!gitCheck)
|
||||
continue;
|
||||
File.WriteAllLines(markdownFile.File, results);
|
||||
File.SetLastWriteTime(markdownFile.File, markdownFile.LastWriteDateTime);
|
||||
result += 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int CircularReference(ILogger<Worker> logger, ReadOnlyDictionary<string, MarkdownFileAndLines> relativeToCollection, ReadOnlyCollection<string> gitOthersModifiedAndDeletedExcludingStandardFiles)
|
||||
{
|
||||
int result = 0;
|
||||
@ -1350,6 +1259,45 @@ internal static partial class HelperMarkdown
|
||||
return new(result?.MarkdownFile, result?.Lines, result?.MarkdownFile.H1, result is null ? null : Path.GetRelativePath(markdownFile.Directory, Path.GetFullPath(result.MarkdownFile.File)));
|
||||
}
|
||||
|
||||
private static int SortFrontMatter(AppSettings appSettings, ILogger<Worker> logger, Input input, ReadOnlyDictionary<string, MarkdownFileAndLines> relativeToCollection, ReadOnlyCollection<string> gitOthersModifiedAndDeletedExcludingStandardFiles)
|
||||
{
|
||||
int result = 0;
|
||||
List<string> results = [];
|
||||
bool gitCheck;
|
||||
string[] lines;
|
||||
string frontMatterYaml;
|
||||
MarkdownFile markdownFile;
|
||||
string[] frontMatterYamlLines;
|
||||
ISerializer serializer = new SerializerBuilder().WithIndentedSequences().Build();
|
||||
foreach (KeyValuePair<string, MarkdownFileAndLines> relativeTo in relativeToCollection)
|
||||
{
|
||||
results.Clear();
|
||||
if (relativeTo.Value.Lines.Length < 2)
|
||||
continue;
|
||||
lines = relativeTo.Value.Lines;
|
||||
markdownFile = relativeTo.Value.MarkdownFile;
|
||||
if (markdownFile.IsKanbanMarkdown)
|
||||
continue;
|
||||
gitCheck = gitOthersModifiedAndDeletedExcludingStandardFiles.Contains(markdownFile.File);
|
||||
if (!gitCheck)
|
||||
continue;
|
||||
if (markdownFile.LineNumber.FrontMatterYamlEnd is null)
|
||||
continue;
|
||||
frontMatterYaml = serializer.Serialize(markdownFile.FrontMatterYaml).Trim();
|
||||
frontMatterYamlLines = frontMatterYaml.Split(Environment.NewLine);
|
||||
results.Add("---");
|
||||
results.AddRange(frontMatterYamlLines);
|
||||
for (int i = markdownFile.LineNumber.FrontMatterYamlEnd.Value; i < lines.Length; i++)
|
||||
results.Add(lines[i]);
|
||||
if (results.Count == lines.Length && string.Join('\r', lines) == string.Join('\r', results))
|
||||
continue;
|
||||
File.WriteAllLines(markdownFile.File, results);
|
||||
File.SetLastWriteTime(markdownFile.File, markdownFile.LastWriteDateTime);
|
||||
result += 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static void MarkdownWikiLinkVerification(AppSettings appSettings, ILogger<Worker> logger, List<string> args, CancellationToken cancellationToken)
|
||||
{
|
||||
int updated;
|
||||
@ -1363,7 +1311,7 @@ internal static partial class HelperMarkdown
|
||||
relativeToCollection = GetRelativeToCollection(appSettings, input, gitOthersModifiedAndDeletedExcludingStandardFiles);
|
||||
logger.LogInformation("{updated} Markdown file(s) were updated", updated);
|
||||
}
|
||||
updated = ConvertFrontMatterToJsonFriendly(relativeToCollection, gitOthersModifiedAndDeletedExcludingStandardFiles);
|
||||
updated = SortFrontMatter(appSettings, logger, input, relativeToCollection, gitOthersModifiedAndDeletedExcludingStandardFiles);
|
||||
if (updated != 0)
|
||||
{
|
||||
relativeToCollection = GetRelativeToCollection(appSettings, input, gitOthersModifiedAndDeletedExcludingStandardFiles);
|
||||
|
77
Worker.cs
77
Worker.cs
@ -87,6 +87,37 @@ public class Worker : BackgroundService
|
||||
}
|
||||
}
|
||||
|
||||
private void LogOptions()
|
||||
{
|
||||
_Logger.LogInformation("A) Save (Top Directory Only),");
|
||||
_Logger.LogInformation("B) Save (All Directories),");
|
||||
_Logger.LogInformation("C) Clipboard (Top Directory Only),");
|
||||
_Logger.LogInformation("D) Clipboard (All Directories),");
|
||||
_Logger.LogInformation("E) Everything delete recursive,");
|
||||
_Logger.LogInformation("F) Find and delete all *.log.* files then empty directories,");
|
||||
_Logger.LogInformation("G) Genealogical Data Communication,");
|
||||
// H
|
||||
_Logger.LogInformation("I) Ignore case and rename files to lowercase,");
|
||||
_Logger.LogInformation("J) Set Date from Json Entry,");
|
||||
_Logger.LogInformation("K) Kanban support,");
|
||||
_Logger.LogInformation("L) Log Merge (APC Log [0-9(8)]_*.log),");
|
||||
_Logger.LogInformation("M) Markdown Wiki Link Verification,");
|
||||
_Logger.LogInformation("N) Create Note Files,");
|
||||
_Logger.LogInformation("O) Oracle tnsNames.ora,");
|
||||
_Logger.LogInformation("P) PDF parse,");
|
||||
// Q
|
||||
_Logger.LogInformation("R) Rename to old, copy, delete old,");
|
||||
_Logger.LogInformation("S) Set Date from Zip Entry,");
|
||||
_Logger.LogInformation("T) *Ticks ~~Too long rename~~,");
|
||||
// U
|
||||
// V
|
||||
// W
|
||||
_Logger.LogInformation("X) Day Helpers,");
|
||||
_Logger.LogInformation("Y) Zip file(s) by directory with file,");
|
||||
_Logger.LogInformation("Z) Zip file(s) by date,");
|
||||
_Logger.LogInformation("Delete) Delete empty directories,");
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!cancellationToken.IsCancellationRequested)
|
||||
@ -109,48 +140,24 @@ public class Worker : BackgroundService
|
||||
consoleKey = ConsoleKey.End;
|
||||
if (singleCharIndex is not null)
|
||||
_Args.RemoveAt(singleCharIndex.Value);
|
||||
_Logger.LogInformation(consoleKey.ToString());
|
||||
if (_Args.Count == 0)
|
||||
{
|
||||
_Logger.LogWarning("Must pass a argument!");
|
||||
CreateWindowsShortcut();
|
||||
}
|
||||
else if (Directory.Exists(_Args[0]) && File.Exists(Path.Combine(_Args[0], string.Concat(Path.GetFileName(_Args[0]), ".dll"))))
|
||||
Helpers.HelperILMerge.ILMerge(_Args[0]);
|
||||
else if (Directory.Exists(_Args[0]))
|
||||
{
|
||||
for (int i = 0; i < int.MaxValue; i++)
|
||||
if (!_ConsoleKeys.Contains(consoleKey))
|
||||
{
|
||||
if (_ConsoleKeys.Contains(consoleKey))
|
||||
break;
|
||||
_Logger.LogInformation("A) Save (Top Directory Only),");
|
||||
_Logger.LogInformation("B) Save (All Directories),");
|
||||
_Logger.LogInformation("C) Clipboard (Top Directory Only),");
|
||||
_Logger.LogInformation("D) Clipboard (All Directories),");
|
||||
_Logger.LogInformation("E) Everything delete recursive,");
|
||||
_Logger.LogInformation("F) Find and delete all *.log.* files then empty directories,");
|
||||
_Logger.LogInformation("G) Genealogical Data Communication,");
|
||||
// H
|
||||
_Logger.LogInformation("I) Ignore case and rename files to lowercase,");
|
||||
_Logger.LogInformation("J) Set Date from Json Entry,");
|
||||
_Logger.LogInformation("K) Kanban support,");
|
||||
_Logger.LogInformation("L) Log Merge (APC Log [0-9(8)]_*.log),");
|
||||
_Logger.LogInformation("M) Markdown Wiki Link Verification,");
|
||||
_Logger.LogInformation("N) Create Note Files,");
|
||||
_Logger.LogInformation("O) Oracle tnsNames.ora,");
|
||||
_Logger.LogInformation("P) PDF parse,");
|
||||
// Q
|
||||
_Logger.LogInformation("R) Rename to old, copy, delete old,");
|
||||
_Logger.LogInformation("S) Set Date from Zip Entry,");
|
||||
_Logger.LogInformation("T) *Ticks ~~Too long rename~~,");
|
||||
// U
|
||||
// V
|
||||
// W
|
||||
_Logger.LogInformation("X) Day Helpers,");
|
||||
_Logger.LogInformation("Y) Zip file(s) by directory with file,");
|
||||
_Logger.LogInformation("Z) Zip file(s) by date,");
|
||||
_Logger.LogInformation("Delete) Delete empty directories,");
|
||||
consoleKey = Console.ReadKey().Key;
|
||||
_Logger.LogInformation(" ");
|
||||
for (int i = 0; i < int.MaxValue; i++)
|
||||
{
|
||||
if (_ConsoleKeys.Contains(consoleKey))
|
||||
break;
|
||||
LogOptions();
|
||||
consoleKey = Console.ReadKey().Key;
|
||||
_Logger.LogInformation(" ");
|
||||
}
|
||||
}
|
||||
switch (consoleKey)
|
||||
{
|
||||
@ -230,7 +237,7 @@ public class Worker : BackgroundService
|
||||
throw new Exception(_Args[0]);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{ _Logger.LogError("{Message}{NewLine}{StackTrace}", ex.Message, Environment.NewLine, ex.StackTrace); }
|
||||
{ _Logger.LogError("{Message}{NewLine}{_Args}{NewLine}{StackTrace}", ex.Message, Environment.NewLine, string.Join(' ', _Args), Environment.NewLine, ex.StackTrace); }
|
||||
if (_IsSilent)
|
||||
_Logger.LogInformation("Done. Bye");
|
||||
else
|
||||
|
Loading…
x
Reference in New Issue
Block a user