save redundancies on exit

This commit is contained in:
nihil 2025-05-10 18:57:49 +02:00
parent 5800f2229f
commit 63c1c88393

View File

@ -38,14 +38,18 @@ namespace RedundancyFinderCLI
}
public override int Execute([NotNull] CommandContext context, [NotNull] Settings settings)
{
var extensions = settings.Extensions.Split(",", StringSplitOptions.RemoveEmptyEntries);
Finder finder = new Finder();
int hashingTasks = 0;
int hashingTasksFinished = 0;
// Register the ProcessExit event to save redundancies on exit
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
{
SaveRedundancies(finder, settings.OutputPath);
};
finder.FileError += (sender, e) =>
{
if (e.Exception is UnauthorizedAccessException)
@ -93,12 +97,8 @@ namespace RedundancyFinderCLI
try
{
var p = AnsiConsole.Progress();
p
.Start(ctx =>
p.Start(ctx =>
{
// Define tasks
//var hashing = ctx.AddTask("[green]Hashing Files[/]",autoStart:false,);
finder.TaskStarted += (sender, e) =>
{
hashingTasks++;
@ -106,7 +106,6 @@ namespace RedundancyFinderCLI
{
WriteLine($"[green]Task started: [/]{e}");
}
//hashing.MaxValue = hashingTasks;
};
finder.FileFound += (sender, e) =>
@ -116,25 +115,12 @@ namespace RedundancyFinderCLI
WriteLine($"[green]File found: [/]{e.FilePath} {GetSizeFormat((ulong)e.Size)} ");
}
hashingTasksFinished++;
//hashing.Value = hashingTasksFinished;
};
//hashing.Value = hashing.MaxValue;
finder.FindRedundancies(settings.SearchPaths, extensions);
//hashing.StopTask();
});
var json = JsonConvert.SerializeObject(finder.Redundancies, Formatting.Indented);
var outputPath = settings.OutputPath;
//check if path is relative or absolute
if (!Path.IsPathRooted(settings.OutputPath))
{
outputPath = Path.Combine(Directory.GetCurrentDirectory(), outputPath);
}
File.WriteAllText(outputPath, json);
WriteLine($"[yellow]Wrote [/]{finder.Redundancies.Count}[yellow] redundancies to [/]'{outputPath}'");
SaveRedundancies(finder, settings.OutputPath);
ulong totalSize = finder.Redundancies.Select(x => (ulong)x.Value.FileSize).Aggregate((a, b) => a + b);
string sizeFormat = GetSizeFormat(totalSize);
@ -152,17 +138,36 @@ namespace RedundancyFinderCLI
}
AnsiConsole.WriteLine();
}
}
}
catch (Exception e)
{
WriteLine($"[red] Error:\n[/]{e.Message}");
}
return 0;
}
private void SaveRedundancies(Finder finder, string outputPath)
{
try
{
var json = JsonConvert.SerializeObject(finder.Redundancies, Formatting.Indented);
// Check if path is relative or absolute
if (!Path.IsPathRooted(outputPath))
{
outputPath = Path.Combine(Directory.GetCurrentDirectory(), outputPath);
}
File.WriteAllText(outputPath, json);
WriteLine($"[yellow]Wrote [/]{finder.Redundancies.Count}[yellow] redundancies to [/]'{outputPath}'");
}
catch (Exception ex)
{
WriteLine($"[red]Failed to save redundancies: {ex.Message}[/]");
}
}
private void WriteLine(string v)
{
string now = Markup.Escape($"[{DateTime.Now.ToString("HH:mm:ss")}]");