Dependency Injection Style
AOT Compiling Switched to Secret from Development json file Added Kanbn Humanizer HelperCreateNoteFiles.CleanExistingFiles HelperPackageFilesByDate Added SRP Helper Hardcoded File Search and Sort Set Date from Zip Entry
This commit is contained in:
@ -5,30 +5,89 @@ namespace File_Folder_Helper.Helpers;
|
||||
internal static class HelperCreateNoteFiles
|
||||
{
|
||||
|
||||
private static void CleanExistingFiles(string directory, long ticks)
|
||||
{
|
||||
string check;
|
||||
string[] lines;
|
||||
string checkFile;
|
||||
string? fileDirectory;
|
||||
string checkDirectory;
|
||||
bool circularReference;
|
||||
string fileNameWithoutExtension;
|
||||
char altDrive = directory[0] is 'c' or 'C' ? 'D' : 'C';
|
||||
string[] files = Directory.GetFiles(directory, "*.md", SearchOption.AllDirectories);
|
||||
string match = ",*** *** *** *** *** *** *** *** ***,*** *** *** *** *** *** *** *** ***,*** *** *** *** *** *** *** *** ***,,TODO:,*** *** *** *** *** *** *** *** ***,*** *** *** *** *** *** *** *** ***,,Notes:,*** *** *** *** *** *** *** *** ***,*** *** *** *** *** *** *** *** ***";
|
||||
foreach (string file in files)
|
||||
{
|
||||
lines = File.ReadAllLines(file);
|
||||
if (lines.Length < 1)
|
||||
continue;
|
||||
circularReference = false;
|
||||
fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (!lines[i].Contains($"[[{fileNameWithoutExtension}]]"))
|
||||
continue;
|
||||
lines[i] = lines[i].Replace("[[", "__").Replace("]]", "__");
|
||||
if (!circularReference)
|
||||
circularReference = true;
|
||||
}
|
||||
if (circularReference)
|
||||
File.WriteAllLines(file, lines);
|
||||
lines[0] = string.Empty;
|
||||
check = string.Join(',', lines);
|
||||
if (check != match)
|
||||
continue;
|
||||
fileDirectory = Path.GetDirectoryName(file);
|
||||
if (string.IsNullOrEmpty(fileDirectory))
|
||||
continue;
|
||||
checkDirectory = $"{altDrive}:/{ticks}/{fileDirectory[3..]}";
|
||||
if (!Directory.Exists(checkDirectory))
|
||||
_ = Directory.CreateDirectory(checkDirectory);
|
||||
checkFile = $"{altDrive}:/{ticks}/{file[3..]}";
|
||||
if (File.Exists(checkFile))
|
||||
continue;
|
||||
File.Move(file, checkFile);
|
||||
}
|
||||
_ = HelperDeleteEmptyDirectories.DeleteEmptyDirectories(directory);
|
||||
}
|
||||
|
||||
internal static void CreateNoteFiles(string argsZero)
|
||||
{
|
||||
string file;
|
||||
string directory;
|
||||
string weekOfYear;
|
||||
DateTime dateTime;
|
||||
DateTime nowDateTime = DateTime.Now;
|
||||
long ticks = DateTime.Now.Ticks;
|
||||
CleanExistingFiles(argsZero, ticks);
|
||||
string lastDirectory = string.Empty;
|
||||
DateTime firstEmail = new(2019, 3, 8);
|
||||
DateTime startDateTime = DateTime.Now.AddDays(1);
|
||||
Calendar calendar = new CultureInfo("en-US").Calendar;
|
||||
const string line = "*** *** *** *** *** *** *** *** ***";
|
||||
double totalDays = new TimeSpan(nowDateTime.AddDays(1000).Ticks - firstEmail.Ticks).TotalDays;
|
||||
double totalDays = new TimeSpan(DateTime.Now.AddDays(1000).Ticks - startDateTime.Ticks).TotalDays;
|
||||
int days = (int)Math.Ceiling(totalDays);
|
||||
for (int i = 0; i < days; i++)
|
||||
{
|
||||
dateTime = firstEmail.AddDays(i);
|
||||
dateTime = startDateTime.AddDays(i);
|
||||
weekOfYear = calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString("00");
|
||||
directory = Path.Combine(argsZero, nowDateTime.Ticks.ToString(), dateTime.ToString("yyyy"), $"Week_{weekOfYear}");
|
||||
directory = Path.Combine(argsZero, ticks.ToString(), dateTime.ToString("yyyy"), $"Week_{weekOfYear}");
|
||||
if (!Directory.Exists(directory))
|
||||
_ = Directory.CreateDirectory(directory);
|
||||
file = string.Concat(Path.Combine(directory, $"{dateTime:yyyy-MM-dd}.txt"));
|
||||
file = string.Concat(Path.Combine(directory, $"{dateTime:yyyy-MM-dd}.md"));
|
||||
if (File.Exists(file))
|
||||
continue;
|
||||
File.WriteAllLines(file, new string[] { dateTime.ToString("dddd"), line, line, line, "", "TODO:", line, line, "", "Notes:", line, line });
|
||||
File.WriteAllLines(file, new string[]
|
||||
{
|
||||
"---",
|
||||
"type: daily-note",
|
||||
$"created: {dateTime:yyyy-MM-dd}",
|
||||
"---",
|
||||
string.Empty,
|
||||
$"# {dateTime:yyyy-MM-dd dddd}",
|
||||
string.Empty,
|
||||
"```bash",
|
||||
string.Empty,
|
||||
"```",
|
||||
});
|
||||
if (directory != lastDirectory)
|
||||
{
|
||||
Directory.SetCreationTime(directory, dateTime);
|
||||
|
82
Helpers/HelperHardcodedFileSearchAndSort.cs
Normal file
82
Helpers/HelperHardcodedFileSearchAndSort.cs
Normal file
@ -0,0 +1,82 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Globalization;
|
||||
|
||||
namespace File_Folder_Helper.Helpers;
|
||||
|
||||
internal static class HelperHardcodedFileSearchAndSort
|
||||
{
|
||||
|
||||
internal static void HardcodedFileSearchAndSort(ILogger log, string sourceDirectory, SearchOption searchOption = SearchOption.TopDirectoryOnly)
|
||||
{
|
||||
bool check;
|
||||
string lines;
|
||||
string checkFile;
|
||||
string? directory;
|
||||
FileInfo fileInfo;
|
||||
string weekOfYear;
|
||||
string checkDirectory;
|
||||
CultureInfo cultureInfo = new("en-US");
|
||||
Calendar calendar = cultureInfo.Calendar;
|
||||
string[] hardcodedValues = new string[]
|
||||
{
|
||||
"BIORAD2",
|
||||
"BIORAD3",
|
||||
"BIORAD4",
|
||||
"BIORAD5",
|
||||
"CDE2",
|
||||
"CDE3",
|
||||
"CDE4",
|
||||
"CDE5",
|
||||
"CDE6",
|
||||
"HGCV1",
|
||||
"HGCV2",
|
||||
"HGCV3",
|
||||
"TENCOR1",
|
||||
"TENCOR2",
|
||||
"TENCOR3",
|
||||
"SP101",
|
||||
"SPV01",
|
||||
"SRP",
|
||||
"Bio-Rad"
|
||||
};
|
||||
string[] files = Directory.GetFiles(sourceDirectory, "*", searchOption);
|
||||
foreach (string file in files)
|
||||
{
|
||||
directory = Path.GetDirectoryName(file);
|
||||
if (string.IsNullOrEmpty(directory))
|
||||
continue;
|
||||
check = false;
|
||||
fileInfo = new(file);
|
||||
weekOfYear = calendar.GetWeekOfYear(fileInfo.LastWriteTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString("00");
|
||||
for (int i = 1; i < 3; i++)
|
||||
{
|
||||
if (check)
|
||||
break;
|
||||
lines = i switch
|
||||
{
|
||||
1 => fileInfo.Name,
|
||||
2 => File.ReadAllText(file),
|
||||
_ => throw new NotImplementedException()
|
||||
};
|
||||
foreach (string hardcodedValue in hardcodedValues)
|
||||
{
|
||||
if (!lines.Contains(hardcodedValue))
|
||||
continue;
|
||||
checkDirectory = Path.Combine(directory, $"{fileInfo.LastWriteTime:yyyy}_Week_{weekOfYear}", fileInfo.LastWriteTime.ToString("yyyy-MM-dd"), hardcodedValue);
|
||||
if (!Directory.Exists(checkDirectory))
|
||||
_ = Directory.CreateDirectory(checkDirectory);
|
||||
checkFile = Path.Combine(checkDirectory, Path.GetFileName(file));
|
||||
if (File.Exists(checkFile) || !File.Exists(file))
|
||||
continue;
|
||||
try
|
||||
{ File.Move(file, checkFile); }
|
||||
catch (Exception) { }
|
||||
check = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
log.LogInformation(sourceDirectory);
|
||||
}
|
||||
|
||||
}
|
82
Helpers/HelperKanbanMetadata.cs
Normal file
82
Helpers/HelperKanbanMetadata.cs
Normal file
@ -0,0 +1,82 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace File_Folder_Helper.Helpers;
|
||||
|
||||
internal static class HelperKanbanMetadata
|
||||
{
|
||||
|
||||
private static List<(int, int, string, FileInfo)> GetCollectionFromIndex(string sourceDirectory, string[] lines)
|
||||
{
|
||||
List<(int, int, string, FileInfo)> results = new();
|
||||
string line;
|
||||
FileInfo fileInfo;
|
||||
string[] segments;
|
||||
int groupCount = 0;
|
||||
string? group = null;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
line = lines[i];
|
||||
if (line.Length < 4)
|
||||
continue;
|
||||
if (line[..3] == "## ")
|
||||
{
|
||||
group = line[3..];
|
||||
groupCount += 1;
|
||||
continue;
|
||||
}
|
||||
if (group is null || line[..3] != "- [" || line[^1] != ')')
|
||||
continue;
|
||||
segments = line.Split("](");
|
||||
if (segments.Length != 2)
|
||||
continue;
|
||||
fileInfo = new(Path.Combine(sourceDirectory, segments[1][..^1]));
|
||||
if (!fileInfo.Exists)
|
||||
continue;
|
||||
results.Add((groupCount, i, group, fileInfo));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
internal static void SetMetadata(ILogger log, Models.AppSettings appSettings, string sourceDirectory)
|
||||
{
|
||||
string statusLine;
|
||||
List<string> lines;
|
||||
LineNumber lineNumber;
|
||||
if (log is null)
|
||||
throw new NullReferenceException();
|
||||
string fullPath = Path.GetFullPath(sourceDirectory);
|
||||
if (!Directory.Exists(fullPath))
|
||||
_ = Directory.CreateDirectory(fullPath);
|
||||
List<(MarkdownFile, string[])> collection;
|
||||
collection = HelperMarkdown.GetCollection(appSettings, HelperMarkdown.GetFiles(appSettings, fullPath));
|
||||
string indexFile = Path.Combine(fullPath, "index.md");
|
||||
if (File.Exists(indexFile))
|
||||
{
|
||||
string[] indexFileLines = File.ReadAllLines(indexFile);
|
||||
List<(int, int, string, FileInfo)> collectionFromIndex = GetCollectionFromIndex(sourceDirectory, indexFileLines);
|
||||
foreach ((int groupCount, int itemLineNumber, string group, FileInfo fileInfo) in collectionFromIndex)
|
||||
{
|
||||
if (itemLineNumber == 0)
|
||||
throw new NotSupportedException();
|
||||
(lines, lineNumber) = HelperMarkdown.GetStatusAndMetaEndLineNumbers(fileInfo);
|
||||
if (!lines.Any())
|
||||
continue;
|
||||
statusLine = $"status: \"{groupCount}-{group}\"";
|
||||
indexFileLines[itemLineNumber] = $"{fileInfo.LastWriteTime.Ticks}~~~{indexFileLines[itemLineNumber]}";
|
||||
if (lineNumber.MetaEnd is null)
|
||||
throw new NotSupportedException($"{nameof(SetMetadata)} must be executed first!");
|
||||
if (lineNumber.Status is null)
|
||||
lines.Insert(lineNumber.MetaEnd.Value, statusLine);
|
||||
else
|
||||
{
|
||||
if (lines[lineNumber.Status.Value] == statusLine)
|
||||
continue;
|
||||
lines[lineNumber.Status.Value] = statusLine;
|
||||
}
|
||||
File.WriteAllLines(fileInfo.FullName, lines);
|
||||
}
|
||||
File.WriteAllLines(indexFile, indexFileLines);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
618
Helpers/HelperMarkdown.cs
Normal file
618
Helpers/HelperMarkdown.cs
Normal file
@ -0,0 +1,618 @@
|
||||
using Humanizer;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace File_Folder_Helper.Helpers;
|
||||
|
||||
internal static partial class HelperMarkdown
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Determines a text file's encoding by analyzing its byte order mark (BOM).
|
||||
/// Defaults to ASCII when detection of the text file's endianness fails.
|
||||
/// </summary>
|
||||
/// <param name="filename">The text file to analyze.</param>
|
||||
/// <returns>The detected encoding.</returns>
|
||||
internal static Encoding? GetEncoding(string filename)
|
||||
{
|
||||
Encoding? result;
|
||||
byte[] bom = new byte[4];
|
||||
using FileStream file = new(filename, FileMode.Open, FileAccess.Read);
|
||||
_ = file.Read(bom, 0, 4);
|
||||
if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76)
|
||||
#pragma warning disable SYSLIB0001
|
||||
result = Encoding.UTF7;
|
||||
#pragma warning restore SYSLIB0001
|
||||
if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf)
|
||||
result = Encoding.UTF8;
|
||||
if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0)
|
||||
result = Encoding.UTF32; //UTF-32LE
|
||||
if (bom[0] == 0xff && bom[1] == 0xfe)
|
||||
result = Encoding.Unicode; //UTF-16LE
|
||||
if (bom[0] == 0xfe && bom[1] == 0xff)
|
||||
result = Encoding.BigEndianUnicode; //UTF-16BE
|
||||
if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff)
|
||||
result = new UTF32Encoding(true, true); //UTF-32BE
|
||||
else
|
||||
result = null;
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static string[] GetFiles(Models.AppSettings appSettings, string directory)
|
||||
{
|
||||
string[] files = Directory.GetFiles(directory, "*.md", SearchOption.AllDirectories).
|
||||
Where(l => !appSettings.Exclude.Any(m => l.Contains(m))).ToArray();
|
||||
return files;
|
||||
}
|
||||
|
||||
private static (string type, string h1) GetTypeAndH1(Models.AppSettings appSettings, string h1, List<string> lines, LineNumber lineNumber)
|
||||
{
|
||||
string type = lineNumber.Type is null ? appSettings.DefaultNoteType : lines[lineNumber.Type.Value].Replace("type: ", string.Empty);
|
||||
string h1FromFile = lineNumber.H1 is null ? h1 : lines[lineNumber.H1.Value][2..];
|
||||
return (type, h1FromFile);
|
||||
}
|
||||
|
||||
internal static (List<string>, LineNumber) GetStatusAndMetaEndLineNumbers(FileInfo fileInfo)
|
||||
{
|
||||
string line;
|
||||
int? h1LineNumber = null;
|
||||
int? typeLineNumber = null;
|
||||
int? statusLineNumber = null;
|
||||
int? createdLineNumber = null;
|
||||
int? updatedLineNumber = null;
|
||||
int? metaEndLineNumber = null;
|
||||
Encoding? encoding = GetEncoding(fileInfo.FullName) ?? Encoding.Default;
|
||||
string[] lines = File.ReadAllLines(fileInfo.FullName, encoding);
|
||||
for (int i = 1; i < lines.Length; i++)
|
||||
{
|
||||
line = lines[i];
|
||||
if (line.Length < 3)
|
||||
continue;
|
||||
if (line[..3] == "---")
|
||||
{
|
||||
metaEndLineNumber = i;
|
||||
continue;
|
||||
}
|
||||
if (line.Length > 6 && line[..6] == "type: ")
|
||||
{
|
||||
typeLineNumber = i;
|
||||
continue;
|
||||
}
|
||||
if (line.Length > 8 && line[..8] == "status: ")
|
||||
{
|
||||
statusLineNumber = i;
|
||||
continue;
|
||||
}
|
||||
if (line.Length > 9 && line[..9] == "created: ")
|
||||
{
|
||||
createdLineNumber = i;
|
||||
continue;
|
||||
}
|
||||
if (line.Length > 9 && line[..9] == "updated: ")
|
||||
{
|
||||
updatedLineNumber = i;
|
||||
continue;
|
||||
}
|
||||
if (h1LineNumber is null && line.Length > 2 && line[..2] == "# ")
|
||||
{
|
||||
h1LineNumber = i;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
LineNumber lineNumber = new(createdLineNumber,
|
||||
h1LineNumber,
|
||||
metaEndLineNumber,
|
||||
statusLineNumber,
|
||||
typeLineNumber,
|
||||
updatedLineNumber);
|
||||
return (lines.ToList(), lineNumber);
|
||||
}
|
||||
|
||||
internal static List<(MarkdownFile, string[])> GetCollection(Models.AppSettings appSettings, string[] files)
|
||||
{
|
||||
List<(MarkdownFile, string[])> results = new();
|
||||
string h1;
|
||||
string type;
|
||||
FileInfo fileInfo;
|
||||
List<string> lines;
|
||||
LineNumber lineNumber;
|
||||
MarkdownFile markdownFile;
|
||||
string fileNameWithoutExtension;
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileInfo = new(file);
|
||||
if (fileInfo.DirectoryName is null)
|
||||
continue;
|
||||
(lines, lineNumber) = GetStatusAndMetaEndLineNumbers(fileInfo);
|
||||
fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.FullName);
|
||||
h1 = fileNameWithoutExtension.ToLower().Hyphenate();
|
||||
if (lines.Any())
|
||||
(type, h1) = GetTypeAndH1(appSettings, h1, lines, lineNumber);
|
||||
else
|
||||
{
|
||||
type = "note";
|
||||
File.WriteAllLines(file, new string[] { "---", $"type: {type}", "---", string.Empty, $"# {h1}" });
|
||||
lines = File.ReadAllLines(file).ToList();
|
||||
}
|
||||
markdownFile = new(file, fileInfo.DirectoryName, fileInfo.Name, fileNameWithoutExtension, fileInfo.Extension, fileInfo.CreationTime, fileInfo.LastWriteTime, lineNumber, type, h1);
|
||||
results.Add(new(markdownFile, lines.ToArray()));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
internal static bool SetFrontMatterAndH1(Models.AppSettings appSettings, List<(MarkdownFile, string[])> collection)
|
||||
{
|
||||
bool result = false;
|
||||
string h1Line;
|
||||
string typeLine;
|
||||
string createdLine;
|
||||
string updatedLine;
|
||||
DateTime creationDateTime;
|
||||
string createdLineCompare;
|
||||
string updatedLineCompare;
|
||||
List<string> results = new();
|
||||
foreach ((MarkdownFile markdownFile, string[] lines) in collection)
|
||||
{
|
||||
if (markdownFile.FileName == "board.md")
|
||||
continue;
|
||||
if (!lines.Any())
|
||||
continue;
|
||||
results.Clear();
|
||||
results.AddRange(lines);
|
||||
creationDateTime = markdownFile.CreationDateTime > markdownFile.LastWriteDateTime ? markdownFile.LastWriteDateTime : markdownFile.CreationDateTime;
|
||||
typeLine = $"type: {appSettings.DefaultNoteType}";
|
||||
h1Line = $"# {markdownFile.FileNameWithoutExtension}";
|
||||
createdLineCompare = $"created: {creationDateTime.ToUniversalTime():yyyy-MM-dd}";
|
||||
createdLine = $"created: {creationDateTime.ToUniversalTime():yyyy-MM-ddTHH:mm:ss.fffZ}";
|
||||
updatedLineCompare = $"updated: {markdownFile.LastWriteDateTime.ToUniversalTime():yyyy-MM-dd}";
|
||||
updatedLine = $"updated: {markdownFile.LastWriteDateTime.ToUniversalTime():yyyy-MM-ddTHH:mm:ss.fffZ}";
|
||||
if (markdownFile.LineNumber.MetaEnd is null)
|
||||
{
|
||||
if (markdownFile.LineNumber.H1 is null)
|
||||
{
|
||||
results.Insert(0, string.Empty);
|
||||
results.Insert(0, h1Line);
|
||||
results.Insert(0, string.Empty);
|
||||
}
|
||||
results.Insert(0, "---");
|
||||
results.Insert(0, updatedLine);
|
||||
results.Insert(0, createdLine);
|
||||
results.Insert(0, typeLine);
|
||||
results.Insert(0, "---");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (markdownFile.LineNumber.H1 is null)
|
||||
{
|
||||
results.Insert(markdownFile.LineNumber.MetaEnd.Value + 1, string.Empty);
|
||||
results.Insert(markdownFile.LineNumber.MetaEnd.Value + 1, h1Line);
|
||||
results.Insert(markdownFile.LineNumber.MetaEnd.Value + 1, string.Empty);
|
||||
}
|
||||
if (markdownFile.LineNumber.Type is null)
|
||||
results.Insert(markdownFile.LineNumber.MetaEnd.Value, typeLine);
|
||||
if (markdownFile.LineNumber.Updated is null)
|
||||
results.Insert(markdownFile.LineNumber.MetaEnd.Value, updatedLine);
|
||||
else
|
||||
{
|
||||
if (results[markdownFile.LineNumber.Updated.Value].Contains('$'))
|
||||
continue;
|
||||
if (results[markdownFile.LineNumber.Updated.Value][..updatedLineCompare.Length] == updatedLineCompare)
|
||||
continue;
|
||||
results[markdownFile.LineNumber.Updated.Value] = updatedLine;
|
||||
}
|
||||
if (markdownFile.LineNumber.Created is null)
|
||||
results.Insert(markdownFile.LineNumber.MetaEnd.Value, createdLine);
|
||||
else if (results[markdownFile.LineNumber.Created.Value][..createdLineCompare.Length] != createdLineCompare)
|
||||
results[markdownFile.LineNumber.Created.Value] = createdLine;
|
||||
}
|
||||
if (!result)
|
||||
result = true;
|
||||
File.WriteAllLines(markdownFile.File, results);
|
||||
File.SetLastWriteTime(markdownFile.File, markdownFile.LastWriteDateTime);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static bool CircularReference(List<(MarkdownFile, string[])> collection)
|
||||
{
|
||||
bool result = false;
|
||||
string line;
|
||||
string check;
|
||||
bool circularReference;
|
||||
foreach ((MarkdownFile markdownFile, string[] lines) in collection)
|
||||
{
|
||||
if (lines.Length < 1)
|
||||
continue;
|
||||
circularReference = false;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
check = $"[[{markdownFile.FileNameWithoutExtension}]]";
|
||||
if (!lines[i].Contains(check))
|
||||
continue;
|
||||
line = lines[i].Replace(check, $"~~{markdownFile.FileName}~~");
|
||||
if (lines[i] == line)
|
||||
continue;
|
||||
lines[i] = line;
|
||||
if (!circularReference)
|
||||
circularReference = true;
|
||||
}
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
check = $"{markdownFile.FileNameWithoutExtension}|{markdownFile.FileNameWithoutExtension}]]";
|
||||
if (!lines[i].Contains(check))
|
||||
continue;
|
||||
line = lines[i].Replace(check, $"~~{markdownFile.FileName}~~");
|
||||
if (lines[i] == line)
|
||||
continue;
|
||||
lines[i] = line;
|
||||
if (!circularReference)
|
||||
circularReference = true;
|
||||
}
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
check = $"[{markdownFile.FileNameWithoutExtension}]({markdownFile.FileName})";
|
||||
if (!lines[i].Contains(check))
|
||||
continue;
|
||||
line = lines[i].Replace(check, $"~~{markdownFile.FileName}~~");
|
||||
if (lines[i] == line)
|
||||
continue;
|
||||
lines[i] = line;
|
||||
if (!circularReference)
|
||||
circularReference = true;
|
||||
}
|
||||
if (circularReference)
|
||||
{
|
||||
if (!result)
|
||||
result = true;
|
||||
File.WriteAllLines(markdownFile.File, lines);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static bool FindReplace(List<(MarkdownFile, string[])> collection)
|
||||
{
|
||||
bool result = false;
|
||||
bool found;
|
||||
string line;
|
||||
string check;
|
||||
foreach ((MarkdownFile markdownFile, string[] lines) in collection)
|
||||
{
|
||||
if (lines.Length < 1)
|
||||
continue;
|
||||
found = false;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
check = $"[[K-A/";
|
||||
if (!lines[i].Contains(check))
|
||||
continue;
|
||||
line = lines[i].Replace(check, "[[.kanbn/Archive/");
|
||||
if (lines[i] == line)
|
||||
continue;
|
||||
lines[i] = line;
|
||||
if (!found)
|
||||
found = true;
|
||||
}
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
check = $"[[K-T/";
|
||||
if (!lines[i].Contains(check))
|
||||
continue;
|
||||
line = lines[i].Replace(check, "[[.kanbn/Tasks/");
|
||||
if (lines[i] == line)
|
||||
continue;
|
||||
lines[i] = line;
|
||||
if (!found)
|
||||
found = true;
|
||||
}
|
||||
if (found)
|
||||
{
|
||||
if (!result)
|
||||
result = true;
|
||||
File.WriteAllLines(markdownFile.File, lines);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Dictionary<string, List<MarkdownFile>> GetKeyValuePairs(List<(MarkdownFile MarkdownFile, string[] Lines)> collection)
|
||||
{
|
||||
Dictionary<string, List<MarkdownFile>> results = new();
|
||||
List<MarkdownFile>? markdownFiles;
|
||||
foreach ((MarkdownFile markdownFile, _) in collection)
|
||||
{
|
||||
if (!results.TryGetValue(markdownFile.FileNameWithoutExtension, out markdownFiles))
|
||||
{
|
||||
results.Add(markdownFile.FileNameWithoutExtension, new());
|
||||
if (!results.TryGetValue(markdownFile.FileNameWithoutExtension, out markdownFiles))
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
markdownFiles.Add(markdownFile);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private static (string?, string?) GetRelativePath(Dictionary<string, List<MarkdownFile>> keyValuePairs, MarkdownFile markdownFile, string file)
|
||||
{
|
||||
string? result;
|
||||
string? match;
|
||||
string? title;
|
||||
List<MarkdownFile>? markdownFiles;
|
||||
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
|
||||
if (keyValuePairs.TryGetValue(fileNameWithoutExtension, out markdownFiles))
|
||||
{
|
||||
if (markdownFiles.Count != 1)
|
||||
(match, title) = (null, null);
|
||||
else
|
||||
(match, title) = (markdownFiles.First().File, markdownFiles.First().H1);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!keyValuePairs.TryGetValue(fileNameWithoutExtension.ToLower(), out markdownFiles))
|
||||
(match, title) = (null, null);
|
||||
else
|
||||
{
|
||||
if (markdownFiles.Count != 1)
|
||||
(match, title) = (null, null);
|
||||
else
|
||||
(match, title) = (markdownFiles.First().File, markdownFiles.First().H1);
|
||||
}
|
||||
}
|
||||
if (match is null)
|
||||
{
|
||||
List<string> files = new();
|
||||
List<string> fileNames = new();
|
||||
foreach (KeyValuePair<string, List<MarkdownFile>> keyValuePair in keyValuePairs)
|
||||
{
|
||||
foreach (MarkdownFile keyValue in keyValuePair.Value)
|
||||
{
|
||||
files.Add(keyValue.File);
|
||||
fileNames.Add(keyValue.FileNameWithoutExtension);
|
||||
}
|
||||
}
|
||||
string[] matches = fileNames.Where(l => l.Length == fileNameWithoutExtension.Length && l.Contains(fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
if (matches.Length == 1)
|
||||
match = matches.First();
|
||||
else
|
||||
{
|
||||
string checkName = fileNameWithoutExtension.ToLower().Replace("%20", "-").Replace(' ', '-');
|
||||
matches = fileNames.Where(l => l.Length == checkName.Length && l.Contains(checkName, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
if (matches.Length == 1)
|
||||
match = matches.First();
|
||||
else
|
||||
{
|
||||
if (!matches.Any())
|
||||
match = null;
|
||||
else
|
||||
{
|
||||
checkName = matches.First();
|
||||
matches = files.Where(l => l.Contains(checkName, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
if (matches.Length == 1)
|
||||
match = matches.First();
|
||||
else
|
||||
{
|
||||
checkName = $"{checkName}{markdownFile.Extension}";
|
||||
matches = files.Where(l => l.EndsWith(checkName, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
if (matches.Length == 1)
|
||||
match = matches.First();
|
||||
else
|
||||
{
|
||||
checkName = $"\\{checkName}";
|
||||
matches = files.Where(l => l.EndsWith(checkName, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
if (matches.Length == 1)
|
||||
match = matches.First();
|
||||
else
|
||||
match = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result = match is null ? null : Path.GetRelativePath(markdownFile.Directory, Path.GetFullPath(match));
|
||||
return (result, title);
|
||||
}
|
||||
|
||||
internal static bool ConvertToRelativePath(List<(MarkdownFile MarkdownFile, string[] Lines)> collection)
|
||||
{
|
||||
bool result = false;
|
||||
bool write;
|
||||
string line;
|
||||
string after;
|
||||
string before;
|
||||
string? title;
|
||||
string[] segmentsA;
|
||||
string[] segmentsB;
|
||||
string[] segmentsC;
|
||||
string? relativePath;
|
||||
Dictionary<string, List<MarkdownFile>> keyValuePairs = GetKeyValuePairs(collection);
|
||||
foreach ((MarkdownFile markdownFile, string[] lines) in collection)
|
||||
{
|
||||
if (lines.Length < 1)
|
||||
continue;
|
||||
write = false;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
segmentsA = lines[i].Split("]]");
|
||||
if (segmentsA.Length is not 2 or 3)
|
||||
continue;
|
||||
segmentsB = segmentsA.First().Split("[[");
|
||||
if (segmentsB.Length is not 2 or 3)
|
||||
continue;
|
||||
after = segmentsA.Last();
|
||||
before = segmentsB.First();
|
||||
segmentsC = segmentsB.Last().Split('|');
|
||||
(relativePath, title) = GetRelativePath(keyValuePairs, markdownFile, segmentsC.First());
|
||||
if (relativePath is null)
|
||||
continue;
|
||||
if (title is null)
|
||||
{
|
||||
title = segmentsC.Last().Humanize(LetterCasing.Title);
|
||||
if (title.Length != segmentsC.Last().Length)
|
||||
title = segmentsC.Last();
|
||||
}
|
||||
line = $"{before}[{title}]({relativePath.Replace('\\', '/')}){after}";
|
||||
if (lines[i] == line)
|
||||
continue;
|
||||
lines[i] = line;
|
||||
if (!write)
|
||||
write = true;
|
||||
}
|
||||
if (write)
|
||||
{
|
||||
if (!result)
|
||||
result = true;
|
||||
File.WriteAllLines(markdownFile.File, lines);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static bool ConvertFileToSlugName(List<(MarkdownFile MarkdownFile, string[] Lines)> collection)
|
||||
{
|
||||
bool result = false;
|
||||
bool write;
|
||||
string h1;
|
||||
string file;
|
||||
string line;
|
||||
string? title;
|
||||
string h1Check;
|
||||
string fileName;
|
||||
string checkName;
|
||||
string? directory;
|
||||
string[] segmentsA;
|
||||
string[] segmentsB;
|
||||
string[] segmentsC;
|
||||
string checkFileName;
|
||||
string segmentsALast;
|
||||
string segmentsBFirst;
|
||||
string relativeDirectory;
|
||||
string formattedRelativeDirectory;
|
||||
Dictionary<string, List<MarkdownFile>> keyValuePairs = GetKeyValuePairs(collection);
|
||||
foreach ((MarkdownFile markdownFile, string[] lines) in collection)
|
||||
{
|
||||
if (markdownFile.FileNameWithoutExtension == "index")
|
||||
continue;
|
||||
if (!File.Exists(markdownFile.File))
|
||||
continue;
|
||||
write = false;
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
segmentsA = lines[i].Split("](");
|
||||
if (segmentsA.Length != 2)
|
||||
continue;
|
||||
segmentsALast = segmentsA.Last();
|
||||
if (segmentsALast.StartsWith("http:") || segmentsALast.StartsWith("https:") || segmentsALast.StartsWith("rdp:") || segmentsALast.StartsWith("onenote:"))
|
||||
continue;
|
||||
segmentsB = segmentsALast.Split(")");
|
||||
if (segmentsB.Length != 2)
|
||||
continue;
|
||||
segmentsBFirst = segmentsB.First();
|
||||
file = Path.GetFullPath(Path.Combine(markdownFile.Directory, segmentsBFirst));
|
||||
fileName = Path.GetFileName(file);
|
||||
directory = Path.GetDirectoryName(file);
|
||||
if (string.IsNullOrEmpty(directory))
|
||||
continue;
|
||||
relativeDirectory = segmentsBFirst[..^fileName.Length];
|
||||
formattedRelativeDirectory = relativeDirectory.Replace(" ", "%20");
|
||||
checkFileName = fileName.ToLower().Replace("%20", "-").Replace(' ', '-');
|
||||
checkName = Path.Combine(directory, checkFileName);
|
||||
segmentsC = segmentsA.First().Split('[');
|
||||
(_, title) = GetRelativePath(keyValuePairs, markdownFile, file);
|
||||
if (title is null)
|
||||
{
|
||||
title = segmentsC.Last().Humanize(LetterCasing.Title);
|
||||
if (title.Length != segmentsC.Last().Length)
|
||||
title = segmentsC.Last();
|
||||
}
|
||||
line = $"{segmentsC.First()}[{title}]({Path.Combine(formattedRelativeDirectory, checkFileName)}){segmentsB.Last()}";
|
||||
if (lines[i] == line)
|
||||
continue;
|
||||
if (fileName.Contains(' ') || fileName.Contains("%20"))
|
||||
{
|
||||
if (!File.Exists(file))
|
||||
continue;
|
||||
if (File.Exists(checkName))
|
||||
continue;
|
||||
File.Move(file, checkName);
|
||||
}
|
||||
else if (fileName != fileName.ToLower())
|
||||
{
|
||||
if (file != checkName)
|
||||
{
|
||||
if (!File.Exists(file))
|
||||
continue;
|
||||
File.Move(file, checkName);
|
||||
}
|
||||
}
|
||||
lines[i] = line;
|
||||
if (!write)
|
||||
write = true;
|
||||
}
|
||||
if (write)
|
||||
{
|
||||
if (!result)
|
||||
result = true;
|
||||
File.WriteAllLines(markdownFile.File, lines);
|
||||
}
|
||||
}
|
||||
if (!result)
|
||||
{
|
||||
foreach ((MarkdownFile markdownFile, string[] lines) in collection)
|
||||
{
|
||||
if (markdownFile.LineNumber.H1 is not null)
|
||||
{
|
||||
h1 = lines[markdownFile.LineNumber.H1.Value];
|
||||
if (h1.Length > 2)
|
||||
{
|
||||
h1Check = $"# {h1[2..].Humanize(LetterCasing.Title)}";
|
||||
if (h1Check.Length == h1.Length && h1Check != h1)
|
||||
{
|
||||
lines[markdownFile.LineNumber.H1.Value] = h1Check;
|
||||
if (!result)
|
||||
result = true;
|
||||
File.WriteAllLines(markdownFile.File, lines);
|
||||
}
|
||||
}
|
||||
}
|
||||
checkFileName = markdownFile.FileName.ToLower().Replace("%20", "-").Replace(' ', '-');
|
||||
if (checkFileName == markdownFile.FileName)
|
||||
continue;
|
||||
if (!File.Exists(markdownFile.File))
|
||||
continue;
|
||||
checkName = Path.Combine(markdownFile.Directory, checkFileName);
|
||||
if (checkName == markdownFile.File)
|
||||
continue;
|
||||
if (!result)
|
||||
result = true;
|
||||
File.Move(markdownFile.File, checkName);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static void MarkdownWikiLinkVerification(Models.AppSettings appSettings, string argsZero)
|
||||
{
|
||||
string fullPath = Path.GetFullPath(argsZero);
|
||||
List<(MarkdownFile MarkdownFile, string[] Lines)> collection;
|
||||
collection = GetCollection(appSettings, GetFiles(appSettings, fullPath));
|
||||
if (SetFrontMatterAndH1(appSettings, collection))
|
||||
collection = GetCollection(appSettings, GetFiles(appSettings, fullPath));
|
||||
if (CircularReference(collection))
|
||||
collection = GetCollection(appSettings, GetFiles(appSettings, fullPath));
|
||||
if (FindReplace(collection))
|
||||
collection = GetCollection(appSettings, GetFiles(appSettings, fullPath));
|
||||
if (ConvertToRelativePath(collection))
|
||||
collection = GetCollection(appSettings, GetFiles(appSettings, fullPath));
|
||||
if (ConvertFileToSlugName(collection))
|
||||
collection = GetCollection(appSettings, GetFiles(appSettings, fullPath));
|
||||
string directory = Path.Combine(Environment.CurrentDirectory, ".vscode");
|
||||
if (!Directory.Exists(directory))
|
||||
{
|
||||
JsonSerializerOptions jsonSerializerOptions = new() { WriteIndented = true };
|
||||
string json = JsonSerializer.Serialize(collection.Select(l => l.MarkdownFile), jsonSerializerOptions);
|
||||
File.WriteAllText($"{DateTime.Now.Ticks}.json", json);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
84
Helpers/HelperPackageFilesByDate.cs
Normal file
84
Helpers/HelperPackageFilesByDate.cs
Normal file
@ -0,0 +1,84 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace File_Folder_Helper.Helpers;
|
||||
|
||||
internal static class HelperPackageFilesByDate
|
||||
{
|
||||
|
||||
public record PackageJson(
|
||||
[property: JsonPropertyName("name")] string Name,
|
||||
[property: JsonPropertyName("time")] Dictionary<string, DateTime> Times,
|
||||
[property: JsonPropertyName("_rev")] string Rev,
|
||||
[property: JsonPropertyName("_id")] string Id
|
||||
);
|
||||
|
||||
internal static void SetDateFromJsonEntry(ILogger log, string sourceDirectory, SearchOption searchOption = SearchOption.AllDirectories)
|
||||
{
|
||||
string json;
|
||||
DateTime dateTime;
|
||||
FileInfo fileInfo;
|
||||
string[] segments;
|
||||
string[] tgzFiles;
|
||||
PackageJson? packageJson;
|
||||
string[] packageJsonFiles;
|
||||
string? packageJsonDirectory;
|
||||
string fileNameWithoutExtension;
|
||||
string packageJsonDirectoryName;
|
||||
List<DateTime> dateTimes = new();
|
||||
if (log is null)
|
||||
throw new NullReferenceException();
|
||||
if (!Directory.Exists(sourceDirectory))
|
||||
_ = Directory.CreateDirectory(sourceDirectory);
|
||||
for (int i = 1; i < 2; i++)
|
||||
{
|
||||
packageJsonFiles = Directory.GetFiles(sourceDirectory, "package.json", searchOption);
|
||||
foreach (string packageJsonFile in packageJsonFiles)
|
||||
{
|
||||
packageJsonDirectory = Path.GetDirectoryName(packageJsonFile);
|
||||
if (string.IsNullOrEmpty(packageJsonDirectory))
|
||||
continue;
|
||||
json = File.ReadAllText(packageJsonFile);
|
||||
packageJson = JsonSerializer.Deserialize<PackageJson>(json);
|
||||
if (packageJson is null || !packageJson.Times.Any())
|
||||
continue;
|
||||
packageJsonDirectoryName = Path.GetFileName(packageJsonDirectory);
|
||||
tgzFiles = Directory.GetFiles(packageJsonDirectory, "*.tgz", SearchOption.TopDirectoryOnly);
|
||||
foreach (string tgzFile in tgzFiles)
|
||||
{
|
||||
dateTimes.Clear();
|
||||
fileNameWithoutExtension = Path.GetFileNameWithoutExtension(tgzFile);
|
||||
segments = fileNameWithoutExtension.Split('-');
|
||||
foreach (string segment in segments)
|
||||
{
|
||||
if (!packageJson.Times.TryGetValue(segment, out dateTime))
|
||||
continue;
|
||||
dateTimes.Add(dateTime);
|
||||
fileInfo = new(tgzFile);
|
||||
if (fileInfo.LastWriteTime != dateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTime);
|
||||
}
|
||||
if (!dateTimes.Any())
|
||||
{
|
||||
if (fileNameWithoutExtension.Length + 1 < packageJsonDirectoryName.Length)
|
||||
continue;
|
||||
if (!packageJson.Times.TryGetValue(fileNameWithoutExtension[(packageJsonDirectoryName.Length + 1)..], out dateTime))
|
||||
continue;
|
||||
dateTimes.Add(dateTime);
|
||||
fileInfo = new(tgzFile);
|
||||
if (fileInfo.LastWriteTime != dateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTime);
|
||||
}
|
||||
}
|
||||
if (!dateTimes.Any())
|
||||
continue;
|
||||
dateTime = dateTimes.Max();
|
||||
fileInfo = new(packageJsonFile);
|
||||
if (fileInfo.LastWriteTime != dateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
using Serilog;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace File_Folder_Helper.Helpers;
|
||||
|
||||
@ -9,14 +9,14 @@ internal static class HelperRenameToOldMoveDeleteOldMerge
|
||||
{
|
||||
string checkDirectory = argsZero[0..^1];
|
||||
if (!Directory.Exists(checkDirectory))
|
||||
log.Information(string.Concat("<", checkDirectory, "> doesn't exist!"));
|
||||
log.LogInformation(string.Concat("<", checkDirectory, "> doesn't exist!"));
|
||||
else
|
||||
{
|
||||
string renameFile;
|
||||
string destinationFile;
|
||||
List<string> deleteFiles = new();
|
||||
string[] moveFiles = Directory.GetFiles(argsZero, "*", SearchOption.TopDirectoryOnly);
|
||||
log.Information(string.Concat("<", moveFiles.Length, "> to move"));
|
||||
log.LogInformation(string.Concat("<", moveFiles.Length, "> to move"));
|
||||
foreach (string moveFile in moveFiles)
|
||||
{
|
||||
destinationFile = string.Concat(checkDirectory, moveFile[argsZero.Length..]);
|
||||
@ -30,7 +30,7 @@ internal static class HelperRenameToOldMoveDeleteOldMerge
|
||||
deleteFiles.Add(renameFile);
|
||||
}
|
||||
}
|
||||
log.Information(string.Concat("<", deleteFiles.Count, "> to delete"));
|
||||
log.LogInformation(string.Concat("<", deleteFiles.Count, "> to delete"));
|
||||
foreach (string deleteFile in deleteFiles)
|
||||
{
|
||||
for (short i = 0; i < short.MaxValue; i++)
|
||||
|
@ -1,4 +1,4 @@
|
||||
using Serilog;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text;
|
||||
|
||||
namespace File_Folder_Helper.Helpers;
|
||||
@ -48,9 +48,9 @@ internal static class HelperSaveOrCopyContents
|
||||
default:
|
||||
throw new Exception();
|
||||
}
|
||||
log.Information("D) Directory, F) File or B) Both?");
|
||||
log.LogInformation("D) Directory, F) File or B) Both?");
|
||||
ConsoleKey dfb = Console.ReadKey().Key;
|
||||
log.Information(string.Empty);
|
||||
log.LogInformation(string.Empty);
|
||||
if (dfb is not ConsoleKey.D and not ConsoleKey.F and not ConsoleKey.B)
|
||||
throw new Exception("Not valid");
|
||||
else
|
||||
@ -160,25 +160,25 @@ internal static class HelperSaveOrCopyContents
|
||||
throw new Exception();
|
||||
}
|
||||
TimeSpan timeSpan = new(DateTime.Now.Ticks - now);
|
||||
log.Information(string.Concat(timeSpan.TotalSeconds, " TotalSeconds"));
|
||||
log.LogInformation(string.Concat(timeSpan.TotalSeconds, " TotalSeconds"));
|
||||
if (alongSideTopDirectoryOnly)
|
||||
{
|
||||
File.WriteAllText(filePathAndName, data.ToString());
|
||||
log.Information("Data written");
|
||||
log.LogInformation("Data written");
|
||||
}
|
||||
else if (clipboardTopDirectoryOnly)
|
||||
{
|
||||
TextCopy.ClipboardService.SetText(data.ToString());
|
||||
log.Information("Data stored in clipboard");
|
||||
log.LogInformation("Data stored in clipboard");
|
||||
}
|
||||
else if (alongSideAllDirectories)
|
||||
{
|
||||
File.AppendAllText(filePathAndName, "Done");
|
||||
log.Information("Data written");
|
||||
log.LogInformation("Data written");
|
||||
}
|
||||
else
|
||||
throw new Exception();
|
||||
log.Information("Press any key to close");
|
||||
log.LogInformation("Press any key to close");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
using Serilog;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Text.RegularExpressions;
|
||||
@ -12,12 +12,15 @@ internal static class HelperZipFilesByDate
|
||||
{
|
||||
string key;
|
||||
bool addFile;
|
||||
string? zipPath;
|
||||
string fileName;
|
||||
string[] segments;
|
||||
string[] subFiles;
|
||||
string weekOfYear;
|
||||
FileInfo fileInfo;
|
||||
string zipDirectory;
|
||||
DateTime creationTime;
|
||||
string? directoryName;
|
||||
DateTime lastWriteTime;
|
||||
DateTime nowDateTime = DateTime.Now;
|
||||
Regex regex = new("[a-zA-Z0-9]{1,}");
|
||||
@ -46,7 +49,10 @@ internal static class HelperZipFilesByDate
|
||||
foreach (string topDirectory in topDirectories)
|
||||
{
|
||||
keyValuePairs.Clear();
|
||||
directoryName = Path.GetDirectoryName(topDirectory);
|
||||
subFiles = Directory.GetFiles(topDirectory, "*", searchOption);
|
||||
zipPath = string.IsNullOrEmpty(directoryName) ? null : Path.Combine(directoryName, "ZipPath");
|
||||
zipDirectory = zipPath is not null && Directory.Exists(zipPath) ? zipPath : topDirectory;
|
||||
foreach (string subFile in subFiles)
|
||||
{
|
||||
addFile = false;
|
||||
@ -98,12 +104,12 @@ internal static class HelperZipFilesByDate
|
||||
}
|
||||
foreach (KeyValuePair<string, List<string>> element in keyValuePairs)
|
||||
{
|
||||
key = Path.Combine(topDirectory, $"{element.Key}.zip");
|
||||
key = Path.Combine(zipDirectory, $"{element.Key}.zip");
|
||||
if (File.Exists(key))
|
||||
{
|
||||
for (short i = 101; i < short.MaxValue; i++)
|
||||
{
|
||||
key = Path.Combine(topDirectory, $"{element.Key}_{i}.zip");
|
||||
key = Path.Combine(zipDirectory, $"{element.Key}_{i}.zip");
|
||||
if (!File.Exists(key))
|
||||
break;
|
||||
}
|
||||
@ -114,18 +120,24 @@ internal static class HelperZipFilesByDate
|
||||
_ = zip.CreateEntryFromFile(file, Path.GetFileName(file));
|
||||
File.Delete(file);
|
||||
}
|
||||
if (zipPath is not null && Directory.Exists(zipPath) && !string.IsNullOrEmpty(directoryName))
|
||||
{
|
||||
try
|
||||
{ Directory.SetLastWriteTime(directoryName, DateTime.Now); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
}
|
||||
subFiles = Directory.GetFiles(topDirectory, "*.zip", SearchOption.TopDirectoryOnly);
|
||||
subFiles = Directory.GetFiles(zipDirectory, "*.zip", SearchOption.TopDirectoryOnly);
|
||||
foreach (string subFile in subFiles)
|
||||
{
|
||||
fileName = Path.GetFileNameWithoutExtension(subFile);
|
||||
segments = fileName.Split('_');
|
||||
if (segments.Length > 2)
|
||||
fileName = string.Concat(segments[0], '_', segments[1], '_', segments[2]);
|
||||
if (weeks.ContainsKey(fileName))
|
||||
if (weeks.TryGetValue(fileName, out DateTime value))
|
||||
{
|
||||
try
|
||||
{ File.SetLastWriteTime(subFile, weeks[fileName]); }
|
||||
{ File.SetLastWriteTime(subFile, value); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
}
|
||||
@ -135,7 +147,93 @@ internal static class HelperZipFilesByDate
|
||||
{ _ = HelperDeleteEmptyDirectories.DeleteEmptyDirectories(topDirectory); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
log.Information(topDirectory);
|
||||
log.LogInformation(topDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void SetDateFromZipEntry(ILogger log, string sourceDirectory, SearchOption searchOption = SearchOption.AllDirectories)
|
||||
{
|
||||
string[] files;
|
||||
string keyFile;
|
||||
string keyFileB;
|
||||
string keyFileC;
|
||||
string checkFile;
|
||||
FileInfo fileInfo;
|
||||
string[] zipFiles;
|
||||
string searchPattern;
|
||||
string? zipDirectory;
|
||||
DateTimeOffset? dateTimeOffset;
|
||||
if (!Directory.Exists(sourceDirectory))
|
||||
_ = Directory.CreateDirectory(sourceDirectory);
|
||||
for (int i = 1; i < 3; i++)
|
||||
{
|
||||
(searchPattern, keyFile, keyFileB, keyFileC) = i switch
|
||||
{
|
||||
1 => ("*.nupkg", ".nuspec", "icon", "readme"),
|
||||
2 => ("*.vsix", ".vsixmanifest", string.Empty, string.Empty),
|
||||
_ => throw new NotSupportedException()
|
||||
};
|
||||
zipFiles = Directory.GetFiles(sourceDirectory, searchPattern, searchOption);
|
||||
foreach (string zipFile in zipFiles)
|
||||
{
|
||||
try
|
||||
{
|
||||
dateTimeOffset = null;
|
||||
fileInfo = new(zipFile);
|
||||
using ZipArchive zip = ZipFile.Open(zipFile, ZipArchiveMode.Read);
|
||||
foreach (ZipArchiveEntry zipArchiveEntry in zip.Entries)
|
||||
{
|
||||
if (!zipArchiveEntry.Name.EndsWith(keyFile))
|
||||
continue;
|
||||
dateTimeOffset = zipArchiveEntry.LastWriteTime;
|
||||
break;
|
||||
}
|
||||
zipDirectory = Path.GetDirectoryName(zipFile);
|
||||
if (dateTimeOffset is null || zipDirectory is null)
|
||||
continue;
|
||||
if (fileInfo.LastWriteTime != dateTimeOffset.Value.LocalDateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.Value.LocalDateTime);
|
||||
files = Directory.GetFiles(zipDirectory, $"*{keyFile}", SearchOption.TopDirectoryOnly);
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileInfo = new(file);
|
||||
if (fileInfo.LastWriteTime != dateTimeOffset.Value.LocalDateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.Value.LocalDateTime);
|
||||
}
|
||||
if (string.IsNullOrEmpty(keyFileB))
|
||||
continue;
|
||||
files = Directory.GetFiles(zipDirectory, keyFileB, SearchOption.TopDirectoryOnly);
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileInfo = new(file);
|
||||
if (fileInfo.LastWriteTime != dateTimeOffset.Value.LocalDateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.Value.LocalDateTime);
|
||||
}
|
||||
if (string.IsNullOrEmpty(keyFileC))
|
||||
continue;
|
||||
files = Directory.GetFiles(zipDirectory, keyFileC, SearchOption.TopDirectoryOnly);
|
||||
foreach (string file in files)
|
||||
{
|
||||
fileInfo = new(file);
|
||||
if (fileInfo.LastWriteTime != dateTimeOffset.Value.LocalDateTime)
|
||||
File.SetLastWriteTime(fileInfo.FullName, dateTimeOffset.Value.LocalDateTime);
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
log.LogInformation($"<{zipFile}> is invalid!");
|
||||
checkFile = string.Concat(zipFile, ".err");
|
||||
for (int e = 0; e < short.MaxValue; e++)
|
||||
{
|
||||
if (!File.Exists(checkFile))
|
||||
break;
|
||||
checkFile = string.Concat(checkFile, e);
|
||||
}
|
||||
try
|
||||
{ File.Move(zipFile, checkFile); }
|
||||
catch (Exception) { log.LogInformation($"<{zipFile}> couldn't be moved!"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
8
Helpers/LineNumber.cs
Normal file
8
Helpers/LineNumber.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace File_Folder_Helper.Helpers;
|
||||
|
||||
public record LineNumber(int? Created,
|
||||
int? H1,
|
||||
int? MetaEnd,
|
||||
int? Status,
|
||||
int? Type,
|
||||
int? Updated);
|
12
Helpers/MarkdownFile.cs
Normal file
12
Helpers/MarkdownFile.cs
Normal file
@ -0,0 +1,12 @@
|
||||
namespace File_Folder_Helper.Helpers;
|
||||
|
||||
public record MarkdownFile(string File,
|
||||
string Directory,
|
||||
string FileName,
|
||||
string FileNameWithoutExtension,
|
||||
string Extension,
|
||||
DateTime CreationDateTime,
|
||||
DateTime LastWriteDateTime,
|
||||
LineNumber LineNumber,
|
||||
string Type,
|
||||
string H1);
|
Reference in New Issue
Block a user