From 3669da30ae951dab52ba83cb88e85ae50fae3198 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=AD=20Climent?= Date: Fri, 7 Jun 2024 23:11:19 +0200 Subject: [PATCH 1/7] Add base for better manager loggers --- src/UniGetUI.PackageEngine.Enums/Enums.cs | 11 ++ .../ManagerLogger.cs | 109 ++++++++++++++++ ...niGetUI.PackageEngine.ManagerLogger.csproj | 32 +++++ .../WinGet.cs | 88 +++++++------ .../WinGetHelpers.cs | 122 +++++++++++------- .../Manager/Classes/ManagerLogger.cs | 115 +++++++++++++++++ .../Manager/PackageManager.cs | 3 + 7 files changed, 394 insertions(+), 86 deletions(-) create mode 100644 src/UniGetUI.PackageEngine.ManagerLogger/ManagerLogger.cs create mode 100644 src/UniGetUI.PackageEngine.ManagerLogger/UniGetUI.PackageEngine.ManagerLogger.csproj create mode 100644 src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs diff --git a/src/UniGetUI.PackageEngine.Enums/Enums.cs b/src/UniGetUI.PackageEngine.Enums/Enums.cs index 6c3a40535..5cda8578a 100644 --- a/src/UniGetUI.PackageEngine.Enums/Enums.cs +++ b/src/UniGetUI.PackageEngine.Enums/Enums.cs @@ -50,4 +50,15 @@ public enum OperationType Uninstall, None } + + public enum LoggableTaskType + { + SearchPackages, + CheckForUpdates, + ListInstalledPackages, + RefreshIndexes, + ListSources, + GetPackageDetails, + GetPackageVersions, + } } diff --git a/src/UniGetUI.PackageEngine.ManagerLogger/ManagerLogger.cs b/src/UniGetUI.PackageEngine.ManagerLogger/ManagerLogger.cs new file mode 100644 index 000000000..e9f349a50 --- /dev/null +++ b/src/UniGetUI.PackageEngine.ManagerLogger/ManagerLogger.cs @@ -0,0 +1,109 @@ +using System.Diagnostics; +using UniGetUI.PackageEngine.ManagerClasses.Manager; + +namespace UniGetUI.PackageEngine.ManagerLogger +{ + public class ManagerLogger + { + public enum OperationType + { + SearchPackages, + CheckUpdates, + ListInstalledPackages, + RefreshIndexes, + ListSources, + GetPackageDetails, + GetPackageVersions, + } + + public class OperationLog + { + ManagerLogger Logger; + OperationType Type; + + string Executable; + string Arguments; + int ReturnCode; + DateTime StartTime; + DateTime? EndTime; + List StdOut = new(); + List StdErr = new(); + bool isComplete = false; + bool isOpen = false; + + public OperationLog(ManagerLogger logger, OperationType type, string executable, string arguments) + { + Type = type; + Logger = logger; + Executable = executable; + Arguments = arguments; + StartTime = DateTime.Now; + isComplete = false; + isOpen = true; + } + + public void AddStdoutLine(string? line) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + if (line != null) + StdOut.Add(line); + } + + public void AddStdoutLines(IEnumerable lines) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + StdOut.Add(line); + } + + public void AddStderrLine(string? line) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + if (line != null) + StdErr.Add(line); + } + + public void AddStderrLines(IEnumerable lines) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + StdErr.Add(line); + } + + public void End() + { + EndTime = DateTime.Now; + isComplete = true; + isOpen = false; + Logger.LoadOperation(this); + } + } + + PackageManager Manager; + List Operations = new(); + + + public ManagerLogger(PackageManager manager) + { + Manager = manager; + } + + private void LoadOperation(OperationLog operation) + { + Operations.Add(operation); + } + + public OperationLog CreateOperationLog(OperationType type, Process process) + { + if (process.StartInfo == null) + throw new Exception("Process instance did not have a valid StartInfo value"); + + return new OperationLog(this, type, process.StartInfo.FileName, process.StartInfo.Arguments); + } + + public OperationLog CreateNativeOperation(OperationType type, string ExtraArgument = "N/A") + { + return new OperationLog(this, type, $"{Manager.Name} native operation", ExtraArgument); + } + } +} diff --git a/src/UniGetUI.PackageEngine.ManagerLogger/UniGetUI.PackageEngine.ManagerLogger.csproj b/src/UniGetUI.PackageEngine.ManagerLogger/UniGetUI.PackageEngine.ManagerLogger.csproj new file mode 100644 index 000000000..a49f91344 --- /dev/null +++ b/src/UniGetUI.PackageEngine.ManagerLogger/UniGetUI.PackageEngine.ManagerLogger.csproj @@ -0,0 +1,32 @@ + + + + net8.0-windows10.0.19041.0 + enable + win-x64 + win-$(Platform) + x64 + 10.0.19041.0 + 10.0.19041.0 + 8.0.204 + true + true + 3.1.0.0 + 3.1.0-alpha0 + UniGetUI + Martí Climent and the contributors + Martí Climent + 3.1.0-alpha0 + 2024, Martí Climent + enable + + + + + + + + + + + diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs index 5ad5b3eeb..bccbdf99c 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs @@ -7,6 +7,7 @@ using UniGetUI.PackageEngine.Enums; using UniGetUI.PackageEngine.ManagerClasses.Manager; using UniGetUI.PackageEngine.PackageClasses; +using Windows.Media.AppBroadcasting; namespace UniGetUI.PackageEngine.Managers.WingetManager @@ -94,38 +95,43 @@ protected override async Task GetAvailableUpdates_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; - p.Start(); + var logger = TaskLogger.CreateLogger(LoggableTaskType.CheckForUpdates, p); - await p.StandardInput.WriteAsync(@" - Set-ExecutionPolicy Bypass -Scope Process -Force - function Print-WinGetPackage { - param ( - [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [string] $Name, - [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [string] $Id, - [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [string] $InstalledVersion, - [Parameter(ValueFromPipelineByPropertyName)] [string[]] $AvailableVersions, - [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [bool] $IsUpdateAvailable, - [Parameter(ValueFromPipelineByPropertyName)] [string] $Source - ) - process { - if($IsUpdateAvailable) - { - Write-Output(""#"" + $Name + ""`t"" + $Id + ""`t"" + $InstalledVersion + ""`t"" + $AvailableVersions[0] + ""`t"" + $Source) - } - } - } - - Get-WinGetPackage | Print-WinGetPackage - - exit + p.Start(); - "); + string command = """ + Set-ExecutionPolicy Bypass -Scope Process -Force + function Print-WinGetPackage { + param ( + [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [string] $Name, + [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [string] $Id, + [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [string] $InstalledVersion, + [Parameter(ValueFromPipelineByPropertyName)] [string[]] $AvailableVersions, + [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [bool] $IsUpdateAvailable, + [Parameter(ValueFromPipelineByPropertyName)] [string] $Source + ) + process { + if($IsUpdateAvailable) + { + Write-Output("#" + $Name + "`t" + $Id + "`t" + $InstalledVersion + "`t" + $AvailableVersions[0] + "`t" + $Source) + } + } + } + + Get-WinGetPackage | Print-WinGetPackage + + exit + + """; + + await p.StandardInput.WriteAsync(command); + p.StandardInput.Close(); + logger.AddToStdIn(command); - string output = ""; string? line; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!line.StartsWith("#")) continue; // The PowerShell script appends a '#' to the beginning of each line to identify the output @@ -138,8 +144,8 @@ function Print-WinGetPackage { Packages.Add(new Package(elements[0][1..], elements[1], elements[2], elements[3], source, this)); } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + logger.Close(); await p.WaitForExitAsync(); return Packages.ToArray(); @@ -161,9 +167,10 @@ protected override async Task GetInstalledPackages_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateLogger(LoggableTaskType.ListInstalledPackages, p); p.Start(); - await p.StandardInput.WriteAsync(@" + var command = """ Set-ExecutionPolicy Bypass -Scope Process -Force function Print-WinGetPackage { param ( @@ -175,21 +182,26 @@ function Print-WinGetPackage { [Parameter(ValueFromPipelineByPropertyName)] [string] $Source ) process { - Write-Output(""#"" + $Name + ""`t"" + $Id + ""`t"" + $InstalledVersion + ""`t"" + $Source) + Write-Output("#" + $Name + "`t" + $Id + "`t" + $InstalledVersion + "`t" + $Source) } } Get-WinGetPackage | Print-WinGetPackage + exit - "); + + """; + + await p.StandardInput.WriteAsync(command); + p.StandardInput.Close(); + logger.AddToStdIn(command); - string output = ""; string? line; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!line.StartsWith("#")) continue; // The PowerShell script appends a '#' to the beginning of each line to identify the output @@ -206,8 +218,7 @@ function Print-WinGetPackage { Packages.Add(new Package(elements[0][1..], elements[1], elements[2], source, this)); } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); return Packages.ToArray(); @@ -354,7 +365,7 @@ public override OperationVeredict GetInstallOperationVeredict(Package package, I StartInfo = new ProcessStartInfo() { FileName = CoreData.GSudoPath, - Arguments = Status.ExecutablePath + " " + Properties.ExecutableCallArgs + " settings --enable InstallerHashOverride", + Arguments = $"\"{Status.ExecutablePath}\"" + Properties.ExecutableCallArgs + " settings --enable InstallerHashOverride", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, @@ -468,8 +479,13 @@ public override async Task RefreshPackageIndexes() StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.RefreshIndexes, p); + p.Start(); + logger.AddToStdOut(await p.StandardOutput.ReadToEndAsync()); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + p.Close(); } } diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs index b1497db36..9d73f8cf9 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs @@ -5,6 +5,7 @@ using UniGetUI.Core.Logging; using UniGetUI.Core.Tools; using UniGetUI.PackageEngine.Classes.Manager.ManagerHelpers; +using UniGetUI.PackageEngine.Enums; using UniGetUI.PackageEngine.PackageClasses; using WindowsPackageManager.Interop; using Deployment = Microsoft.Management.Deployment; @@ -58,9 +59,12 @@ public NativeWinGetHelper() public async Task FindPackages_UnSafe(WinGet ManagerInstance, string query) { + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.SearchPackages); + List Packages = new(); FindPackagesOptions PackageFilters = Factory.CreateFindPackagesOptions(); + logger.AddToStdOut("Generating filters..."); // Name filter PackageMatchFilter FilterName = Factory.CreatePackageMatchFilter(); FilterName.Field = Deployment.PackageMatchField.Name; @@ -76,10 +80,12 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string PackageFilters.Filters.Add(FilterId); // Load catalogs + logger.AddToStdOut("Loading available catalogs..."); IReadOnlyList AvailableCatalogs = WinGetManager.GetPackageCatalogs(); Dictionary> FindPackageTasks = new(); // Spawn Tasks to find packages on catalogs + logger.AddToStdOut("Spawning catalog fetching tasks..."); foreach (PackageCatalogReference CatalogReference in AvailableCatalogs.ToArray()) { // Connect to catalog @@ -101,18 +107,19 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string } catch (Exception e) { - Logger.Error("WinGet: Catalog " + CatalogReference.Info.Name + " failed to spawn FindPackages task."); - Logger.Error(e); + logger.AddToStdOut("WinGet: Catalog " + CatalogReference.Info.Name + " failed to spawn FindPackages task."); + logger.AddToStdOut(e.ToString()); } } else { - Logger.Error("WinGet: Catalog " + CatalogReference.Info.Name + " failed to connect."); + logger.AddToStdOut("WinGet: Catalog " + CatalogReference.Info.Name + " failed to connect."); } } // Wait for tasks completion await Task.WhenAll(FindPackageTasks.Values.ToArray()); + logger.AddToStdOut($"All catalogs fetched. Fetching results for query {query}"); foreach (KeyValuePair> CatalogTaskPair in FindPackageTasks) { @@ -124,11 +131,13 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string FindPackagesResult FoundPackages = CatalogTaskPair.Value.Result; foreach (MatchResult package in FoundPackages.Matches.ToArray()) { + var catPkg = package.CatalogPackage; // Create the Package item and add it to the list + logger.AddToStdOut($"Found package: {catPkg.Name}|{catPkg.Name}|{catPkg.DefaultInstallVersion.Version} on catalog {source.Name}"); Packages.Add(new Package( - package.CatalogPackage.Name, - package.CatalogPackage.Id, - package.CatalogPackage.DefaultInstallVersion.Version, + catPkg.Name, + catPkg.Id, + catPkg.DefaultInstallVersion.Version, source, ManagerInstance )); @@ -136,38 +145,43 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string } catch (Exception e) { - Logger.Error("WinGet: Catalog " + CatalogTaskPair.Key.Info.Name + " failed to get available packages."); - Logger.Error(e); + logger.AddToStdErr("WinGet: Catalog " + CatalogTaskPair.Key.Info.Name + " failed to get available packages."); + logger.AddToStdErr(e.ToString()); } } - + logger.Close(); return Packages.ToArray(); } public async Task GetSources_UnSafe(WinGet ManagerInstance) { List sources = new(); + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.ListSources); foreach (PackageCatalogReference catalog in await Task.Run(() => WinGetManager.GetPackageCatalogs().ToArray())) try { + logger.AddToStdOut($"Found source {catalog.Info.Name} with argument {catalog.Info.Argument}"); sources.Add(new ManagerSource(ManagerInstance, catalog.Info.Name, new Uri(catalog.Info.Argument), updateDate: catalog.Info.LastUpdateTime.ToString())); } catch (Exception e) { - Logger.Error(e); + logger.AddToStdErr(e.ToString()); } - + logger.Close(); return sources.ToArray(); } public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Package package) { + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.GetPackageVersions); + // Find the native package for the given Package object PackageCatalogReference Catalog = WinGetManager.GetPackageCatalogByName(package.Source.Name); if (Catalog == null) { - Logger.Error("Failed to get catalog " + package.Source.Name + ". Is the package local?"); + logger.AddToStdErr("Failed to get catalog " + package.Source.Name + ". Is the package local?"); + logger.Close(); return []; } @@ -176,7 +190,8 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa ConnectResult ConnectResult = await Task.Run(() => Catalog.Connect()); if (ConnectResult.Status != Deployment.ConnectResultStatus.Ok) { - Logger.Error("Failed to connect to catalog " + package.Source.Name); + logger.AddToStdErr("Failed to connect to catalog " + package.Source.Name); + logger.Close(); return []; } @@ -192,19 +207,25 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa if (SearchResult.Result == null || SearchResult.Result.Matches == null || SearchResult.Result.Matches.Count() == 0) { - Logger.Error("WinGet: Failed to find package " + package.Id + " in catalog " + package.Source.Name); + logger.AddToStdErr("WinGet: Failed to find package " + package.Id + " in catalog " + package.Source.Name); + logger.Close(); return []; } // Get the Native Package CatalogPackage NativePackage = SearchResult.Result.Matches.First().CatalogPackage; - return NativePackage.AvailableVersions.Select(x => x.Version).ToArray(); + var versions = NativePackage.AvailableVersions.Select(x => x.Version).ToArray(); + foreach (var version in versions) logger.AddToStdOut(version); + logger.Close(); + return versions; } public async Task GetPackageDetails_UnSafe(WinGet ManagerInstance, Package package) { PackageDetails details = new(package); + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.GetPackageDetails); + if (package.Source.Name == "winget") details.ManifestUrl = new Uri("https://github.com/microsoft/winget-pkgs/tree/master/manifests/" + package.Id[0].ToString().ToLower() + "/" @@ -218,7 +239,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc PackageCatalogReference Catalog = WinGetManager.GetPackageCatalogByName(package.Source.Name); if (Catalog == null) { - Logger.Error("Failed to get catalog " + package.Source.Name + ". Is the package local?"); + logger.AddToStdErr("Failed to get catalog " + package.Source.Name + ". Is the package local?"); return details; } @@ -227,7 +248,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc ConnectResult ConnectResult = await Task.Run(() => Catalog.Connect()); if (ConnectResult.Status != Deployment.ConnectResultStatus.Ok) { - Logger.Error("Failed to connect to catalog " + package.Source.Name); + logger.AddToStdErr("Failed to connect to catalog " + package.Source.Name); return details; } @@ -243,7 +264,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc if (SearchResult.Result == null || SearchResult.Result.Matches == null || SearchResult.Result.Matches.Count() == 0) { - Logger.Error("WinGet: Failed to find package " + package.Id + " in catalog " + package.Source.Name); + logger.AddToStdErr("WinGet: Failed to find package " + package.Id + " in catalog " + package.Source.Name); return details; } @@ -303,8 +324,10 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc string? _line; while ((_line = await process.StandardOutput.ReadLineAsync()) != null) if (_line.Trim() != "") + { + logger.AddToStdOut(_line); output.Add(_line); - + } // Parse the output foreach (string __line in output) { @@ -331,7 +354,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc Logger.Warn(e.Message); } } - + logger.Close(); return details; } } @@ -364,10 +387,9 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string p.Start(); + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.SearchPackages, p); - p.Start(); - - await p.StandardInput.WriteAsync(@" + var command = """ Set-ExecutionPolicy Bypass -Scope Process -Force function Print-WinGetPackage { param ( @@ -381,22 +403,21 @@ function Print-WinGetPackage { } } - if(!(Get-Command -Verb Find -Noun WinGetPackage)) - { - Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false - Install-Module -Name Microsoft.WinGet.Client -Scope CurrentUser -AllowClobber -Confirm:$false -Force - } - Find-WinGetPackage -Query """ + query + @""" | Print-WinGetPackage - exit + Find-WinGetPackage -Query {query} | Print-WinGetPackage + exit + - "); + """; + + await p.StandardInput.WriteAsync(command); + p.StandardInput.Close(); + logger.AddToStdIn(command); string? line; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!line.StartsWith("#")) continue; // The PowerShell script appends a '#' to the beginning of each line to identify the output @@ -409,9 +430,9 @@ function Print-WinGetPackage { Packages.Add(new Package(elements[0][1..], elements[1], elements[2], source, ManagerInstance)); } - output += await p.StandardError.ReadToEndAsync(); - // AppTools.LogManagerOperation(ManagerInstance, p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + logger.Close(); return Packages.ToArray(); @@ -633,15 +654,16 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa } }; + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.GetPackageVersions, p); + p.Start(); string? line; List versions = new(); bool DashesPassed = false; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!DashesPassed) { if (line.Contains("---")) @@ -650,8 +672,9 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa else versions.Add(line.Trim()); } - output += await p.StandardError.ReadToEndAsync(); - // AppTools.LogManagerOperation(ManagerInstance, p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(); return versions.ToArray(); } @@ -659,8 +682,8 @@ public async Task GetSources_UnSafe(WinGet ManagerInstance) { List sources = new(); - Process process = new(); - ProcessStartInfo startInfo = new() + Process p = new(); + p.StartInfo = new() { FileName = ManagerInstance.Status.ExecutablePath, Arguments = ManagerInstance.Properties.ExecutableCallArgs + " source list", @@ -672,15 +695,15 @@ public async Task GetSources_UnSafe(WinGet ManagerInstance) StandardOutputEncoding = System.Text.Encoding.UTF8 }; - process.StartInfo = startInfo; - process.Start(); + p.Start(); + + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.SearchPackages, p); bool dashesPassed = false; - string output = ""; string? line; - while ((line = await process.StandardOutput.ReadLineAsync()) != null) + while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); try { if (string.IsNullOrEmpty(line)) @@ -704,10 +727,9 @@ public async Task GetSources_UnSafe(WinGet ManagerInstance) } } - output += await process.StandardError.ReadToEndAsync(); - // AppTools.LogManagerOperation(ManagerInstance, process, output); - - await process.WaitForExitAsync(); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(); return sources.ToArray(); } diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs new file mode 100644 index 000000000..487e698fb --- /dev/null +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs @@ -0,0 +1,115 @@ +using System.Diagnostics; +using UniGetUI.PackageEngine.ManagerClasses.Manager; +using UniGetUI.PackageEngine.Enums; + +namespace UniGetUI.PackageEngine.ManagerClasses.Classes +{ + public class ManagerLogger + { + + + public class TaskLogger + { + ManagerLogger Logger; + LoggableTaskType Type; + + string Executable; + string Arguments; + int ReturnCode; + DateTime StartTime; + DateTime? EndTime; + List StdIn = new(); + List StdOut = new(); + List StdErr = new(); + bool isComplete = false; + bool isOpen = false; + + public TaskLogger(ManagerLogger logger, LoggableTaskType type, string executable, string arguments) + { + Type = type; + Logger = logger; + Executable = executable; + Arguments = arguments; + StartTime = DateTime.Now; + isComplete = false; + isOpen = true; + } + + ~TaskLogger() { + if (isOpen) + throw new Exception("A TaskLogger instance went out of scope without being closed"); + } + + public void AddToStdIn(string? line) + { + if (line != null) AddToStdIn(line.Split('\n')); + } + + public void AddToStdIn(IEnumerable lines) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + StdErr.Add(line); + } + + public void AddToStdOut(string? line) + { + if (line != null) AddToStdOut(line.Split('\n')); + } + + public void AddToStdOut(IEnumerable lines) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + StdOut.Add(line); + } + + public void AddToStdErr(string? line) + { + if (line != null) AddToStdErr(line.Split('\n')); + } + + public void AddToStdErr(IEnumerable lines) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + StdErr.Add(line); + } + + public void Close() + { + EndTime = DateTime.Now; + isComplete = true; + isOpen = false; + Logger.LoadOperation(this); + } + } + + PackageManager Manager; + List Operations = new(); + + + public ManagerLogger(PackageManager manager) + { + Manager = manager; + } + + private void LoadOperation(TaskLogger operation) + { + Operations.Add(operation); + } + + public TaskLogger CreateNew(LoggableTaskType type, Process process) + { + if (process.StartInfo == null) + throw new Exception("Process instance did not have a valid StartInfo value"); + + return new TaskLogger(this, type, process.StartInfo.FileName, process.StartInfo.Arguments); + } + + public TaskLogger CreateNew(LoggableTaskType type, string ExtraArgument = "N/A") + { + return new TaskLogger(this, type, $"{Manager.Name} native operation", ExtraArgument); + } + } +} diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/PackageManager.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/PackageManager.cs index 45ce3207b..ca170d2d2 100644 --- a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/PackageManager.cs +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/PackageManager.cs @@ -11,6 +11,7 @@ using UniGetUI.PackageEngine.Classes.Manager.Providers; using UniGetUI.PackageEngine.Classes.Packages; using UniGetUI.PackageEngine.Enums; +using UniGetUI.PackageEngine.ManagerClasses.Classes; using UniGetUI.PackageEngine.PackageClasses; namespace UniGetUI.PackageEngine.ManagerClasses.Manager @@ -26,6 +27,7 @@ public abstract class PackageManager : SingletonBase, ISourcePro public static string[] FALSE_PACKAGE_IDS = new string[] { "" }; public static string[] FALSE_PACKAGE_VERSIONS = new string[] { "" }; public bool ManagerReady { get; set; } = false; + public ManagerLogger TaskLogger; public BaseSourceProvider? SourceProvider; public BasePackageDetailsProvider? PackageDetailsProvider; @@ -36,6 +38,7 @@ public PackageManager() DefaultSource = Properties.DefaultSource; Name = Properties.Name; __base_constructor_called = true; + TaskLogger = new ManagerLogger(this); } From 21fbf7f0e60e08d3427b540fc6d0deafc01a3477 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=AD=20Climent?= Date: Sat, 8 Jun 2024 23:37:49 +0200 Subject: [PATCH 2/7] Implement interface changes to support new PackageManager Task Logger --- .../WinGet.cs | 8 +- .../WinGetHelpers.cs | 43 +-- .../Manager/Classes/ManagerLogger.cs | 300 +++++++++++++----- src/UniGetUI/Interface/Pages/LogPage.xaml | 2 +- src/UniGetUI/Interface/Pages/LogPage.xaml.cs | 106 +++++-- 5 files changed, 340 insertions(+), 119 deletions(-) diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs index bccbdf99c..488d14388 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs @@ -95,7 +95,7 @@ protected override async Task GetAvailableUpdates_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; - var logger = TaskLogger.CreateLogger(LoggableTaskType.CheckForUpdates, p); + var logger = TaskLogger.CreateNew(LoggableTaskType.CheckForUpdates, p); p.Start(); @@ -145,8 +145,8 @@ function Print-WinGetPackage { } logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); - logger.Close(); await p.WaitForExitAsync(); + logger.Close(); return Packages.ToArray(); } @@ -167,7 +167,7 @@ protected override async Task GetInstalledPackages_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; - var logger = TaskLogger.CreateLogger(LoggableTaskType.ListInstalledPackages, p); + var logger = TaskLogger.CreateNew(LoggableTaskType.ListInstalledPackages, p); p.Start(); var command = """ @@ -220,6 +220,7 @@ function Print-WinGetPackage { logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + logger.Close(); return Packages.ToArray(); } @@ -484,6 +485,7 @@ public override async Task RefreshPackageIndexes() p.Start(); logger.AddToStdOut(await p.StandardOutput.ReadToEndAsync()); logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + logger.Close(); await p.WaitForExitAsync(); p.Close(); } diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs index 9d73f8cf9..69523de2d 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs @@ -64,7 +64,7 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string List Packages = new(); FindPackagesOptions PackageFilters = Factory.CreateFindPackagesOptions(); - logger.AddToStdOut("Generating filters..."); + logger.Log("Generating filters..."); // Name filter PackageMatchFilter FilterName = Factory.CreatePackageMatchFilter(); FilterName.Field = Deployment.PackageMatchField.Name; @@ -80,12 +80,12 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string PackageFilters.Filters.Add(FilterId); // Load catalogs - logger.AddToStdOut("Loading available catalogs..."); + logger.Log("Loading available catalogs..."); IReadOnlyList AvailableCatalogs = WinGetManager.GetPackageCatalogs(); Dictionary> FindPackageTasks = new(); // Spawn Tasks to find packages on catalogs - logger.AddToStdOut("Spawning catalog fetching tasks..."); + logger.Log("Spawning catalog fetching tasks..."); foreach (PackageCatalogReference CatalogReference in AvailableCatalogs.ToArray()) { // Connect to catalog @@ -107,19 +107,19 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string } catch (Exception e) { - logger.AddToStdOut("WinGet: Catalog " + CatalogReference.Info.Name + " failed to spawn FindPackages task."); - logger.AddToStdOut(e.ToString()); + logger.Error("WinGet: Catalog " + CatalogReference.Info.Name + " failed to spawn FindPackages task."); + logger.Error(e); } } else { - logger.AddToStdOut("WinGet: Catalog " + CatalogReference.Info.Name + " failed to connect."); + logger.Error("WinGet: Catalog " + CatalogReference.Info.Name + " failed to connect."); } } // Wait for tasks completion await Task.WhenAll(FindPackageTasks.Values.ToArray()); - logger.AddToStdOut($"All catalogs fetched. Fetching results for query {query}"); + logger.Log($"All catalogs fetched. Fetching results for query {query}"); foreach (KeyValuePair> CatalogTaskPair in FindPackageTasks) { @@ -133,7 +133,7 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string { var catPkg = package.CatalogPackage; // Create the Package item and add it to the list - logger.AddToStdOut($"Found package: {catPkg.Name}|{catPkg.Name}|{catPkg.DefaultInstallVersion.Version} on catalog {source.Name}"); + logger.Log($"Found package: {catPkg.Name}|{catPkg.Name}|{catPkg.DefaultInstallVersion.Version} on catalog {source.Name}"); Packages.Add(new Package( catPkg.Name, catPkg.Id, @@ -145,8 +145,8 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string } catch (Exception e) { - logger.AddToStdErr("WinGet: Catalog " + CatalogTaskPair.Key.Info.Name + " failed to get available packages."); - logger.AddToStdErr(e.ToString()); + logger.Error("WinGet: Catalog " + CatalogTaskPair.Key.Info.Name + " failed to get available packages."); + logger.Error(e); } } logger.Close(); @@ -161,12 +161,12 @@ public async Task GetSources_UnSafe(WinGet ManagerInstance) foreach (PackageCatalogReference catalog in await Task.Run(() => WinGetManager.GetPackageCatalogs().ToArray())) try { - logger.AddToStdOut($"Found source {catalog.Info.Name} with argument {catalog.Info.Argument}"); + logger.Log($"Found source {catalog.Info.Name} with argument {catalog.Info.Argument}"); sources.Add(new ManagerSource(ManagerInstance, catalog.Info.Name, new Uri(catalog.Info.Argument), updateDate: catalog.Info.LastUpdateTime.ToString())); } catch (Exception e) { - logger.AddToStdErr(e.ToString()); + logger.Error(e); } logger.Close(); return sources.ToArray(); @@ -180,7 +180,7 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa PackageCatalogReference Catalog = WinGetManager.GetPackageCatalogByName(package.Source.Name); if (Catalog == null) { - logger.AddToStdErr("Failed to get catalog " + package.Source.Name + ". Is the package local?"); + logger.Error("Failed to get catalog " + package.Source.Name + ". Is the package local?"); logger.Close(); return []; } @@ -190,7 +190,7 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa ConnectResult ConnectResult = await Task.Run(() => Catalog.Connect()); if (ConnectResult.Status != Deployment.ConnectResultStatus.Ok) { - logger.AddToStdErr("Failed to connect to catalog " + package.Source.Name); + logger.Error("Failed to connect to catalog " + package.Source.Name); logger.Close(); return []; } @@ -207,7 +207,7 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa if (SearchResult.Result == null || SearchResult.Result.Matches == null || SearchResult.Result.Matches.Count() == 0) { - logger.AddToStdErr("WinGet: Failed to find package " + package.Id + " in catalog " + package.Source.Name); + logger.Error("Failed to find package " + package.Id + " in catalog " + package.Source.Name); logger.Close(); return []; } @@ -215,7 +215,7 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa // Get the Native Package CatalogPackage NativePackage = SearchResult.Result.Matches.First().CatalogPackage; var versions = NativePackage.AvailableVersions.Select(x => x.Version).ToArray(); - foreach (var version in versions) logger.AddToStdOut(version); + foreach (var version in versions) logger.Log(version); logger.Close(); return versions; } @@ -239,7 +239,8 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc PackageCatalogReference Catalog = WinGetManager.GetPackageCatalogByName(package.Source.Name); if (Catalog == null) { - logger.AddToStdErr("Failed to get catalog " + package.Source.Name + ". Is the package local?"); + logger.Error("Failed to get catalog " + package.Source.Name + ". Is the package local?"); + logger.Close(); return details; } @@ -248,7 +249,8 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc ConnectResult ConnectResult = await Task.Run(() => Catalog.Connect()); if (ConnectResult.Status != Deployment.ConnectResultStatus.Ok) { - logger.AddToStdErr("Failed to connect to catalog " + package.Source.Name); + logger.Error("Failed to connect to catalog " + package.Source.Name); + logger.Close(); return details; } @@ -264,7 +266,8 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc if (SearchResult.Result == null || SearchResult.Result.Matches == null || SearchResult.Result.Matches.Count() == 0) { - logger.AddToStdErr("WinGet: Failed to find package " + package.Id + " in catalog " + package.Source.Name); + logger.Error("WinGet: Failed to find package " + package.Id + " in catalog " + package.Source.Name); + logger.Close(); return details; } @@ -325,7 +328,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc while ((_line = await process.StandardOutput.ReadLineAsync()) != null) if (_line.Trim() != "") { - logger.AddToStdOut(_line); + logger.Log(_line); output.Add(_line); } // Parse the output diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs index 487e698fb..91d332b13 100644 --- a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs @@ -1,115 +1,273 @@ using System.Diagnostics; using UniGetUI.PackageEngine.ManagerClasses.Manager; using UniGetUI.PackageEngine.Enums; +using UniGetUI.Core.Logging; +using System.Text; namespace UniGetUI.PackageEngine.ManagerClasses.Classes { public class ManagerLogger { - + PackageManager Manager; + public List Operations = new(); - public class TaskLogger + public ManagerLogger(PackageManager manager) { - ManagerLogger Logger; - LoggableTaskType Type; + Manager = manager; + } - string Executable; - string Arguments; - int ReturnCode; - DateTime StartTime; - DateTime? EndTime; - List StdIn = new(); - List StdOut = new(); - List StdErr = new(); - bool isComplete = false; - bool isOpen = false; + public ProcessTaskLogger CreateNew(LoggableTaskType type, Process process) + { + if (process.StartInfo == null) + throw new Exception("Process instance did not have a valid StartInfo value"); - public TaskLogger(ManagerLogger logger, LoggableTaskType type, string executable, string arguments) - { - Type = type; - Logger = logger; - Executable = executable; - Arguments = arguments; - StartTime = DateTime.Now; - isComplete = false; - isOpen = true; - } + var operation = new ProcessTaskLogger(Manager, type, process.StartInfo.FileName, process.StartInfo.Arguments); + Operations.Add(operation); + return operation; + } - ~TaskLogger() { - if (isOpen) - throw new Exception("A TaskLogger instance went out of scope without being closed"); - } + public NativeTaskLogger CreateNew(LoggableTaskType type) + { + var operation = new NativeTaskLogger(Manager, type); + Operations.Add(operation); + return operation; + } + } + + public abstract class TaskLogger + { + protected DateTime StartTime; + protected DateTime? EndTime; + protected bool isComplete = false; + protected bool isOpen = false; + protected IEnumerable? CachedMessage = null; + protected IEnumerable? CachedVerboseMessage = null; - public void AddToStdIn(string? line) - { - if (line != null) AddToStdIn(line.Split('\n')); - } + public TaskLogger() + { + StartTime = DateTime.Now; + isComplete = false; + isOpen = true; + } - public void AddToStdIn(IEnumerable lines) - { - if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); - foreach (string line in lines) - StdErr.Add(line); - } + ~TaskLogger() + { + if(isOpen) Close(); + } - public void AddToStdOut(string? line) - { - if (line != null) AddToStdOut(line.Split('\n')); - } + public void Close() + { + EndTime = DateTime.Now; + isOpen = false; + isComplete = true; + CachedMessage = null; + CachedVerboseMessage = null; + } - public void AddToStdOut(IEnumerable lines) - { - if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); - foreach (string line in lines) - StdOut.Add(line); - } + /// + /// Returns the output with a preceeding digit representing the color of the line: + /// 0. White + /// 1. Grey + /// 2. Red + /// 3. Blue + /// + /// + public abstract IEnumerable AsColoredString(bool verbose = false); + } - public void AddToStdErr(string? line) + public class ProcessTaskLogger : TaskLogger + { + PackageManager Manager; + LoggableTaskType Type; + + string Executable; + string Arguments; + int ReturnCode; + List StdIn = new(); + List StdOut = new(); + List StdErr = new(); + + public ProcessTaskLogger(PackageManager manager, LoggableTaskType type, string executable, string arguments) : base() + { + Type = type; + Manager = manager; + Executable = executable; + Arguments = arguments; + } + + public void AddToStdIn(string? line) + { + if (line != null) AddToStdIn(line.Split('\n')); + } + + public void AddToStdIn(IEnumerable lines) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + if(line != "") StdIn.Add(line); + } + + public void AddToStdOut(string? line) + { + if (line != null) AddToStdOut(line.Split('\n')); + } + + public void AddToStdOut(IEnumerable lines) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + if (line != "") StdOut.Add(line); + } + + public void AddToStdErr(string? line) + { + if (line != null) AddToStdErr(line.Split('\n')); + } + + public void AddToStdErr(IEnumerable lines) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + if (line != "") StdErr.Add(line); + } + + public override IEnumerable AsColoredString(bool verbose = false) + { + if (!verbose && CachedMessage != null && isComplete) + return CachedMessage; + else if (verbose && CachedVerboseMessage != null && isComplete) + return CachedVerboseMessage; + + List result = new(); + result.Add($"0Logged subprocess-based task on manager {Manager.Name}. Task type is {Type}"); + result.Add($"0Subprocess executable: \"{Executable}\""); + result.Add($"0Command-line arguments: \"{Arguments}\""); + result.Add($"0Process start time: {StartTime}"); + if (EndTime == null) + result.Add($"2Process end time: UNFINISHED"); + else + result.Add($"0Process end time: {EndTime}"); + if (StdIn.Count > 0) { - if (line != null) AddToStdErr(line.Split('\n')); + result.Add("0"); + result.Add("0-- Process STDIN"); + if(verbose) + foreach (var line in StdIn) + result.Add("3" + line); + else + result.Add("1 ..."); } - - public void AddToStdErr(IEnumerable lines) + if (StdOut.Count > 0) { - if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); - foreach (string line in lines) - StdErr.Add(line); + result.Add("0"); + result.Add("0-- Process STDOUT"); + if(verbose) + foreach (var line in StdOut) + result.Add("1" + line); + else + result.Add("1 ..."); } - - public void Close() + if (StdErr.Count > 0) { - EndTime = DateTime.Now; - isComplete = true; - isOpen = false; - Logger.LoadOperation(this); + result.Add("0"); + result.Add("0-- Process STDERR"); + foreach (var line in StdErr) + result.Add("2" + line); } + result.Add("0"); + result.Add("0——————————————————————————————————————————"); + result.Add("0"); + + if(verbose) + return CachedVerboseMessage = result; + else + return CachedMessage = result; } + } + public class NativeTaskLogger : TaskLogger + { PackageManager Manager; - List Operations = new(); + LoggableTaskType Type; + int ReturnCode; + List Info = new(); + List Errors = new(); - public ManagerLogger(PackageManager manager) + public NativeTaskLogger(PackageManager manager, LoggableTaskType type) : base() { + Type = type; Manager = manager; } - private void LoadOperation(TaskLogger operation) + public void Log(IEnumerable lines) { - Operations.Add(operation); + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + if (line != "") Info.Add(line); } - public TaskLogger CreateNew(LoggableTaskType type, Process process) + public void Log(string? line) { - if (process.StartInfo == null) - throw new Exception("Process instance did not have a valid StartInfo value"); + if (line != null) Log(line.Split('\n')); + } + + public void Error(IEnumerable lines) + { + if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + foreach (string line in lines) + if (line != "") Errors.Add(line); + } - return new TaskLogger(this, type, process.StartInfo.FileName, process.StartInfo.Arguments); + public void Error(string? line) + { + if (line != null) Error(line.Split('\n')); } - public TaskLogger CreateNew(LoggableTaskType type, string ExtraArgument = "N/A") + public void Error(Exception? e) { - return new TaskLogger(this, type, $"{Manager.Name} native operation", ExtraArgument); + if (e != null) Error(e.ToString().Split('\n')); + } + + public override IEnumerable AsColoredString(bool verbose = false) + { + if (!verbose && CachedMessage != null && isComplete) + return CachedMessage; + else if (verbose && CachedVerboseMessage != null && isComplete) + return CachedVerboseMessage; + + List result = new List(); + result.Add($"0Logged native task on manager {Manager.Name}. Task type is {Type}"); + result.Add($"0Process start time: {StartTime}"); + if (EndTime == null) + result.Add($"2Process end time: UNFINISHED"); + else + result.Add($"0Process end time: {EndTime}"); + if (Info.Count > 0) + { + result.Add("0"); + result.Add("0-- Task information"); + if (verbose) + foreach (var line in Info) + result.Add("1" + line); + else + result.Add("1 ..."); + } + if (Errors.Count > 0) + { + result.Add("0"); + result.Add("0-- Task errors"); + foreach (var line in Errors) + result.Add("2" + line); + } + result.Add("0"); + result.Add("0——————————————————————————————————————————"); + result.Add("0"); + + if (verbose) + return CachedVerboseMessage = result; + else + return CachedMessage = result; } } } diff --git a/src/UniGetUI/Interface/Pages/LogPage.xaml b/src/UniGetUI/Interface/Pages/LogPage.xaml index 0393fc319..4b0f9338c 100644 --- a/src/UniGetUI/Interface/Pages/LogPage.xaml +++ b/src/UniGetUI/Interface/Pages/LogPage.xaml @@ -41,7 +41,7 @@ - + diff --git a/src/UniGetUI/Interface/Pages/LogPage.xaml.cs b/src/UniGetUI/Interface/Pages/LogPage.xaml.cs index 0eebd1ebf..852551299 100644 --- a/src/UniGetUI/Interface/Pages/LogPage.xaml.cs +++ b/src/UniGetUI/Interface/Pages/LogPage.xaml.cs @@ -38,12 +38,32 @@ public Logger_LogPage(Logger_LogType logger_LogType = Logger_LogType.UniGetUILog Logger_LogType = logger_LogType; LoadLog(); - LogLevelCombo.Items.Add(CoreTools.Translate("1 - Errors")); - LogLevelCombo.Items.Add(CoreTools.Translate("2 - Warnings")); - LogLevelCombo.Items.Add(CoreTools.Translate("3 - Information (less)")); - LogLevelCombo.Items.Add(CoreTools.Translate("4 - Information (more)")); - LogLevelCombo.Items.Add(CoreTools.Translate("5 - information (debug)")); - LogLevelCombo.SelectedIndex = 3; + + if (Logger_LogType == Logger_LogType.UniGetUILog) + { + LogLevelCombo.Items.Clear(); + LogLevelCombo.Items.Add(CoreTools.Translate("1 - Errors")); + LogLevelCombo.Items.Add(CoreTools.Translate("2 - Warnings")); + LogLevelCombo.Items.Add(CoreTools.Translate("3 - Information (less)")); + LogLevelCombo.Items.Add(CoreTools.Translate("4 - Information (more)")); + LogLevelCombo.Items.Add(CoreTools.Translate("5 - information (debug)")); + LogLevelCombo.SelectedIndex = 3; + } else if (Logger_LogType == Logger_LogType.ManagerLogs) + { + LogLevelCombo.Items.Clear(); + foreach (var manager in MainApp.Instance.PackageManagerList) + { + LogLevelCombo.Items.Add(manager.Name); + LogLevelCombo.Items.Add($"{manager.Name} ({CoreTools.Translate("Verbose")})"); + } + LogLevelCombo.SelectedIndex = 0; + } + else + { + LogLevelCombo.Items.Clear(); + LogLevelCombo.Items.Add(CoreTools.Translate("Operation log")); + LogLevelCombo.SelectedIndex = 0; + } } public void SetText(string body) @@ -63,24 +83,24 @@ public void SetText(string body) public void LoadLog() { - + // Dark theme colors + Color DARK_GREY = Color.FromArgb(255, 130, 130, 130); + Color DARK_BLUE = Color.FromArgb(255, 190, 190, 190); + Color DARK_WHITE = Color.FromArgb(255, 250, 250, 250); + Color DARK_YELLOW = Color.FromArgb(255, 255, 255, 90); + Color DARK_RED = Color.FromArgb(255, 255, 80, 80); + + // Light theme colors + Color LIGHT_GREY = Color.FromArgb(255, 125, 125, 225); + Color LIGHT_BLUE = Color.FromArgb(255, 50, 50, 150); + Color LIGHT_WHITE = Color.FromArgb(255, 0, 0, 0); + Color LIGHT_YELLOW = Color.FromArgb(255, 150, 150, 0); + Color LIGHT_RED = Color.FromArgb(255, 205, 0, 0); + + bool IS_DARK = MainApp.Instance.ThemeListener.CurrentTheme == ApplicationTheme.Dark; + if (Logger_LogType == Logger_LogType.UniGetUILog) { - // Dark theme colors - Color DARK_GREY = Color.FromArgb(255, 130, 130, 130); - Color DARK_BLUE = Color.FromArgb(255, 190, 190, 190); - Color DARK_WHITE = Color.FromArgb(255, 250, 250, 250); - Color DARK_YELLOW = Color.FromArgb(255, 255, 255, 90); - Color DARK_RED = Color.FromArgb(255, 255, 80, 80); - - // Light theme colors - Color LIGHT_GREY = Color.FromArgb(255, 125, 125, 225); - Color LIGHT_BLUE = Color.FromArgb(255, 50, 50, 150); - Color LIGHT_WHITE = Color.FromArgb(255, 0, 0, 0); - Color LIGHT_YELLOW = Color.FromArgb(255, 150, 150, 0); - Color LIGHT_RED = Color.FromArgb(255, 205, 0, 0); - - bool IS_DARK = MainApp.Instance.ThemeListener.CurrentTheme == ApplicationTheme.Dark; LogEntry[] logs = Logger.GetLogs(); LogTextBox.Blocks.Clear(); @@ -139,11 +159,49 @@ public void LoadLog() ((Run)p.Inlines[^1]).Text = ((Run)p.Inlines[^1]).Text.TrimEnd(); LogTextBox.Blocks.Add(p); } - //SetText(text); + MainScroller.ScrollToVerticalOffset(MainScroller.ScrollableHeight); } + else if (Logger_LogType == Logger_LogType.ManagerLogs) { - SetText(CoreData.ManagerLogs); + bool verbose = LogLevelCombo.SelectedValue?.ToString()?.Contains("(") ?? false; + foreach (var manager in MainApp.Instance.PackageManagerList) + if (manager.Name == LogLevelCombo.SelectedValue?.ToString()?.Split(' ')[0]) + { + var TaskLogger = manager.TaskLogger; + LogTextBox.Blocks.Clear(); + foreach (var operation in TaskLogger.Operations) + { + Paragraph p = new(); + foreach (var line in operation.AsColoredString(verbose)) + { + Brush color; + switch (line[0]) + { + case '0': + color = new SolidColorBrush { Color = IS_DARK ? DARK_WHITE : LIGHT_WHITE}; + break; + case '1': + color = new SolidColorBrush { Color = IS_DARK ? DARK_GREY : LIGHT_GREY }; + break; + case '2': + color = new SolidColorBrush { Color = IS_DARK ? DARK_RED : LIGHT_RED }; + break; + case '3': + color = new SolidColorBrush { Color = IS_DARK ? DARK_BLUE : LIGHT_BLUE }; + break; + default: + color = new SolidColorBrush { Color = IS_DARK ? DARK_YELLOW : LIGHT_YELLOW }; + break; + } + p.Inlines.Add(new Run() { Text = line[1..] + "\n", Foreground = color }); + } + ((Run)p.Inlines[^1]).Text = ((Run)p.Inlines[^1]).Text.TrimEnd(); + LogTextBox.Blocks.Add(p); + } + break; + } + MainScroller.ScrollToVerticalOffset(MainScroller.ScrollableHeight); } else if (Logger_LogType == Logger_LogType.OperationHistory) { From 777e824c625027b820023002f34c84604cd59342 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=AD=20Climent?= Date: Sun, 9 Jun 2024 15:46:50 +0200 Subject: [PATCH 3/7] Update exception texts --- .../Manager/Classes/ManagerLogger.cs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs index 91d332b13..c6f18073b 100644 --- a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs @@ -1,8 +1,6 @@ using System.Diagnostics; using UniGetUI.PackageEngine.ManagerClasses.Manager; using UniGetUI.PackageEngine.Enums; -using UniGetUI.Core.Logging; -using System.Text; namespace UniGetUI.PackageEngine.ManagerClasses.Classes { @@ -19,7 +17,7 @@ public ManagerLogger(PackageManager manager) public ProcessTaskLogger CreateNew(LoggableTaskType type, Process process) { if (process.StartInfo == null) - throw new Exception("Process instance did not have a valid StartInfo value"); + throw new Exception("Given process instance did not have a valid StartInfo value"); var operation = new ProcessTaskLogger(Manager, type, process.StartInfo.FileName, process.StartInfo.Arguments); Operations.Add(operation); @@ -102,7 +100,7 @@ public void AddToStdIn(string? line) public void AddToStdIn(IEnumerable lines) { - if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + if (!isOpen) throw new Exception("Attempted to write log into an already-closed ProcessTaskLogger"); foreach (string line in lines) if(line != "") StdIn.Add(line); } @@ -114,7 +112,7 @@ public void AddToStdOut(string? line) public void AddToStdOut(IEnumerable lines) { - if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + if (!isOpen) throw new Exception("Attempted to write log into an already-closed ProcessTaskLogger"); foreach (string line in lines) if (line != "") StdOut.Add(line); } @@ -126,7 +124,7 @@ public void AddToStdErr(string? line) public void AddToStdErr(IEnumerable lines) { - if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + if (!isOpen) throw new Exception("Attempted to write log into an already-closed ProcessTaskLogger"); foreach (string line in lines) if (line != "") StdErr.Add(line); } @@ -202,7 +200,7 @@ public NativeTaskLogger(PackageManager manager, LoggableTaskType type) : base() public void Log(IEnumerable lines) { - if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + if (!isOpen) throw new Exception("Attempted to write log into an already-closed NativeTaskLogger"); foreach (string line in lines) if (line != "") Info.Add(line); } @@ -214,7 +212,7 @@ public void Log(string? line) public void Error(IEnumerable lines) { - if (!isOpen) throw new Exception("Attempted to write log into an already-closed OperationLog"); + if (!isOpen) throw new Exception("Attempted to write log into an already-closed NativeTaskLogger"); foreach (string line in lines) if (line != "") Errors.Add(line); } From 66168966772d2ee3c5efd128da51328096187640 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=AD=20Climent?= Date: Sun, 9 Jun 2024 16:38:38 +0200 Subject: [PATCH 4/7] Improvements to logger, migrate Scoop to new manager ntask logger --- src/UniGetUI.PackageEngine.Enums/Enums.cs | 33 +++++++++++-- .../Scoop.cs | 47 +++++++++++------- .../ScoopPackageDetailsProvider.cs | 20 +++++--- .../ScoopSourceProvider.cs | 39 +++++++-------- .../WinGet.cs | 10 ++-- .../WinGetHelpers.cs | 40 +++++++++------ .../Manager/Classes/ManagerLogger.cs | 33 +++++++++---- src/UniGetUI/Interface/Pages/LogPage.xaml.cs | 49 +++++++++++++------ 8 files changed, 177 insertions(+), 94 deletions(-) diff --git a/src/UniGetUI.PackageEngine.Enums/Enums.cs b/src/UniGetUI.PackageEngine.Enums/Enums.cs index 5cda8578a..f15b6a9f4 100644 --- a/src/UniGetUI.PackageEngine.Enums/Enums.cs +++ b/src/UniGetUI.PackageEngine.Enums/Enums.cs @@ -53,12 +53,37 @@ public enum OperationType public enum LoggableTaskType { + /// + /// Installs a required dependency for a Package Manager + /// + InstallManagerDependency, + /// + /// Searches for packages with a specific query + /// SearchPackages, - CheckForUpdates, - ListInstalledPackages, + /// + /// Lists all the available updates + /// + ListUpdates, + /// + /// Lists the installed packages + /// + ListPackages, + /// + /// Refreshes the package indexes + /// RefreshIndexes, + /// + /// Lists the available sources for the manager + /// ListSources, - GetPackageDetails, - GetPackageVersions, + /// + /// Loads the package details for a specific package + /// + LoadPackageDetails, + /// + /// Loads the available versions for a specific package + /// + LoadPackageVersions, } } diff --git a/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs b/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs index d91073d72..445491d77 100644 --- a/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs +++ b/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs @@ -81,11 +81,17 @@ protected override async Task FindPackages_UnSafe(string query) FileName = Status.ExecutablePath, Arguments = Properties.ExecutableCallArgs + " install main/scoop-search", UseShellExecute = true, + RedirectStandardOutput = true, + RedirectStandardError = true, CreateNoWindow = true } }; + var aux_logger = TaskLogger.CreateNew(LoggableTaskType.InstallManagerDependency, proc); proc.Start(); + aux_logger.AddToStdOut(await proc.StandardOutput.ReadToEndAsync()); + aux_logger.AddToStdErr(await proc.StandardError.ReadToEndAsync()); await proc.WaitForExitAsync(); + aux_logger.Close(proc.ExitCode); path = "scoop-search.exe"; } @@ -102,15 +108,15 @@ protected override async Task FindPackages_UnSafe(string query) StandardOutputEncoding = System.Text.Encoding.UTF8 } }; + var logger = TaskLogger.CreateNew(LoggableTaskType.SearchPackages, p); p.Start(); string? line; ManagerSource source = Properties.DefaultSource; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (line.StartsWith("'")) { string sourceName = line.Split(" ")[0].Replace("'", ""); @@ -130,8 +136,9 @@ protected override async Task FindPackages_UnSafe(string query) Packages.Add(new Package(Core.Tools.CoreTools.FormatAsName(elements[0]), elements[0], elements[1].Replace("(", "").Replace(")", ""), source, this)); } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); return Packages.ToArray(); } @@ -146,6 +153,7 @@ protected override async Task GetAvailableUpdates_UnSafe() List Packages = new(); + Process p = new() { StartInfo = new ProcessStartInfo() @@ -159,15 +167,15 @@ protected override async Task GetAvailableUpdates_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 } }; + var logger = TaskLogger.CreateNew(LoggableTaskType.ListUpdates, p); p.Start(); string? line; bool DashesPassed = false; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!DashesPassed) { if (line.Contains("---")) @@ -193,8 +201,9 @@ protected override async Task GetAvailableUpdates_UnSafe() Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], elements[2], InstalledPackages[elements[0] + "." + elements[1]].Source, this, InstalledPackages[elements[0] + "." + elements[1]].Scope)); } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); return Packages.ToArray(); } @@ -215,15 +224,14 @@ protected override async Task GetInstalledPackages_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 } }; - + var logger = TaskLogger.CreateNew(LoggableTaskType.ListPackages, p); p.Start(); string? line; bool DashesPassed = false; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!DashesPassed) { if (line.Contains("---")) @@ -247,8 +255,9 @@ protected override async Task GetInstalledPackages_UnSafe() Packages.Add(new Package(Core.Tools.CoreTools.FormatAsName(elements[0]), elements[0], elements[1], GetSourceOrDefault(elements[2]), this, scope)); } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); return Packages.ToArray(); } @@ -357,7 +366,7 @@ public override async Task RefreshPackageIndexes() return; } LastScoopSourceUpdateTime = DateTime.Now.Ticks; - Process process = new(); + Process p = new(); ProcessStartInfo StartInfo = new() { FileName = Status.ExecutablePath, @@ -369,9 +378,13 @@ public override async Task RefreshPackageIndexes() CreateNoWindow = true, StandardOutputEncoding = System.Text.Encoding.UTF8 }; - process.StartInfo = StartInfo; - process.Start(); - await process.WaitForExitAsync(); + p.StartInfo = StartInfo; + var logger = TaskLogger.CreateNew(LoggableTaskType.RefreshIndexes, p); + p.Start(); + logger.AddToStdOut(await p.StandardOutput.ReadToEndAsync()); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); } protected override async Task LoadManager() diff --git a/src/UniGetUI.PackageEngine.Managers.Scoop/ScoopPackageDetailsProvider.cs b/src/UniGetUI.PackageEngine.Managers.Scoop/ScoopPackageDetailsProvider.cs index 5b917f66d..cee632ae5 100644 --- a/src/UniGetUI.PackageEngine.Managers.Scoop/ScoopPackageDetailsProvider.cs +++ b/src/UniGetUI.PackageEngine.Managers.Scoop/ScoopPackageDetailsProvider.cs @@ -4,6 +4,7 @@ using UniGetUI.Core.Logging; using UniGetUI.Core.Tools; using UniGetUI.PackageEngine.Classes.Manager.BaseProviders; +using UniGetUI.PackageEngine.ManagerClasses.Classes; using UniGetUI.PackageEngine.ManagerClasses.Manager; using UniGetUI.PackageEngine.PackageClasses; @@ -40,8 +41,12 @@ protected override async Task GetPackageDetails_Unsafe(Package p StandardOutputEncoding = System.Text.Encoding.UTF8, }; + var logger = Manager.TaskLogger.CreateNew(Enums.LoggableTaskType.LoadPackageDetails, p); + p.Start(); string JsonString = await p.StandardOutput.ReadToEndAsync(); + logger.AddToStdOut(JsonString); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); JsonObject? RawInfo = JsonObject.Parse(JsonString) as JsonObject; @@ -62,7 +67,7 @@ protected override async Task GetPackageDetails_Unsafe(Package p else if (RawInfo.ContainsKey("description")) details.Description = CoreTools.GetStringOrNull(RawInfo["description"]?.ToString()); } - catch (Exception ex) { Logger.Debug("[Scoop] Can't load description: " + ex); } + catch (Exception ex) { logger.AddToStdErr("Can't load description: " + ex); } try { @@ -71,7 +76,7 @@ protected override async Task GetPackageDetails_Unsafe(Package p else details.InstallerType = CoreTools.Translate("Scoop package"); } - catch (Exception ex) { Logger.Debug("[Scoop] Can't load installer type: " + ex); } + catch (Exception ex) { logger.AddToStdErr("Can't load installer type: " + ex); } try { @@ -84,7 +89,7 @@ protected override async Task GetPackageDetails_Unsafe(Package p details.Author = details.HomepageUrl?.Host.Split(".")[^2]; } } - catch (Exception ex) { Logger.Debug("[Scoop] Can't load homepage: " + ex); } + catch (Exception ex) { logger.AddToStdErr("Can't load homepage: " + ex); } try { @@ -98,7 +103,7 @@ protected override async Task GetPackageDetails_Unsafe(Package p else if (RawInfo.ContainsKey("notes")) details.ReleaseNotes = RawInfo["notes"]?.ToString(); } - catch (Exception ex) { Logger.Debug("[Scoop] Can't load notes: " + ex); } + catch (Exception ex) { logger.AddToStdErr("Can't load notes: " + ex); } try { @@ -113,7 +118,7 @@ protected override async Task GetPackageDetails_Unsafe(Package p details.License = RawInfo["license"]?.ToString(); } } - catch (Exception ex) { Logger.Debug("[Scoop] Can't load license: " + ex); } + catch (Exception ex) { logger.AddToStdErr("Can't load license: " + ex); } try { @@ -138,15 +143,16 @@ protected override async Task GetPackageDetails_Unsafe(Package p details.InstallerSize = await CoreTools.GetFileSizeAsync(details.InstallerUrl); } - catch (Exception ex) { Logger.Debug("[Scoop] Can't load installer URL: " + ex); } + catch (Exception ex) { logger.AddToStdErr("Can't load installer URL: " + ex); } try { if (RawInfo.ContainsKey("checkver") && RawInfo["checkver"] is JsonObject && ((RawInfo["checkver"] as JsonObject)?.ContainsKey("url") ?? false)) details.ReleaseNotesUrl = CoreTools.GetUriOrNull(RawInfo["checkver"]?["url"]?.ToString() ?? ""); } - catch (Exception ex) { Logger.Debug("[Scoop] Can't load notes URL: " + ex); } + catch (Exception ex) { logger.AddToStdErr("Can't load notes URL: " + ex); } + logger.Close(0); return details; } diff --git a/src/UniGetUI.PackageEngine.Managers.Scoop/ScoopSourceProvider.cs b/src/UniGetUI.PackageEngine.Managers.Scoop/ScoopSourceProvider.cs index 7448898cb..3e5d1aac5 100644 --- a/src/UniGetUI.PackageEngine.Managers.Scoop/ScoopSourceProvider.cs +++ b/src/UniGetUI.PackageEngine.Managers.Scoop/ScoopSourceProvider.cs @@ -34,29 +34,30 @@ public override string[] GetRemoveSourceParameters(ManagerSource source) protected override async Task GetSources_UnSafe() { - using (Process process = new()) + using (Process p = new()) { - process.StartInfo.FileName = Manager.Status.ExecutablePath; - process.StartInfo.Arguments = Manager.Properties.ExecutableCallArgs + " bucket list"; - process.StartInfo.RedirectStandardOutput = true; - process.StartInfo.RedirectStandardError = true; - process.StartInfo.RedirectStandardInput = true; - process.StartInfo.UseShellExecute = false; - process.StartInfo.CreateNoWindow = true; - process.StartInfo.StandardInputEncoding = System.Text.Encoding.UTF8; - process.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8; + p.StartInfo.FileName = Manager.Status.ExecutablePath; + p.StartInfo.Arguments = Manager.Properties.ExecutableCallArgs + " bucket list"; + p.StartInfo.RedirectStandardOutput = true; + p.StartInfo.RedirectStandardError = true; + p.StartInfo.RedirectStandardInput = true; + p.StartInfo.UseShellExecute = false; + p.StartInfo.CreateNoWindow = true; + p.StartInfo.StandardInputEncoding = System.Text.Encoding.UTF8; + p.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8; + + var logger = Manager.TaskLogger.CreateNew(LoggableTaskType.ListSources, p); List sources = new(); - process.Start(); + p.Start(); - string _output = ""; bool DashesPassed = false; string? line; - while ((line = await process.StandardOutput.ReadLineAsync()) != null) + while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - _output += line + "\n"; + logger.AddToStdOut(line); try { if (!DashesPassed) @@ -80,12 +81,10 @@ protected override async Task GetSources_UnSafe() Logger.Warn(e); } } - _output += await process.StandardError.ReadToEndAsync(); - Manager.LogOperation(process, _output); - - await process.WaitForExitAsync(); - - + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); + return sources.ToArray(); } } diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs index 488d14388..b7c7cdc29 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs @@ -95,7 +95,7 @@ protected override async Task GetAvailableUpdates_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; - var logger = TaskLogger.CreateNew(LoggableTaskType.CheckForUpdates, p); + var logger = TaskLogger.CreateNew(LoggableTaskType.ListUpdates, p); p.Start(); @@ -146,7 +146,7 @@ function Print-WinGetPackage { logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); - logger.Close(); + logger.Close(p.ExitCode); return Packages.ToArray(); } @@ -167,7 +167,7 @@ protected override async Task GetInstalledPackages_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; - var logger = TaskLogger.CreateNew(LoggableTaskType.ListInstalledPackages, p); + var logger = TaskLogger.CreateNew(LoggableTaskType.ListPackages, p); p.Start(); var command = """ @@ -220,7 +220,7 @@ function Print-WinGetPackage { logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); - logger.Close(); + logger.Close(p.ExitCode); return Packages.ToArray(); } @@ -485,7 +485,7 @@ public override async Task RefreshPackageIndexes() p.Start(); logger.AddToStdOut(await p.StandardOutput.ReadToEndAsync()); logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); - logger.Close(); + logger.Close(p.ExitCode); await p.WaitForExitAsync(); p.Close(); } diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs index 69523de2d..9c9b427bf 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs @@ -149,7 +149,7 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string logger.Error(e); } } - logger.Close(); + logger.Close(0); return Packages.ToArray(); } @@ -163,25 +163,26 @@ public async Task GetSources_UnSafe(WinGet ManagerInstance) { logger.Log($"Found source {catalog.Info.Name} with argument {catalog.Info.Argument}"); sources.Add(new ManagerSource(ManagerInstance, catalog.Info.Name, new Uri(catalog.Info.Argument), updateDate: catalog.Info.LastUpdateTime.ToString())); + logger.Close(0); } catch (Exception e) { logger.Error(e); + logger.Close(1); } - logger.Close(); return sources.ToArray(); } public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Package package) { - var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.GetPackageVersions); + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.LoadPackageVersions); // Find the native package for the given Package object PackageCatalogReference Catalog = WinGetManager.GetPackageCatalogByName(package.Source.Name); if (Catalog == null) { logger.Error("Failed to get catalog " + package.Source.Name + ". Is the package local?"); - logger.Close(); + logger.Close(1); return []; } @@ -191,7 +192,7 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa if (ConnectResult.Status != Deployment.ConnectResultStatus.Ok) { logger.Error("Failed to connect to catalog " + package.Source.Name); - logger.Close(); + logger.Close(1); return []; } @@ -208,7 +209,7 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa if (SearchResult.Result == null || SearchResult.Result.Matches == null || SearchResult.Result.Matches.Count() == 0) { logger.Error("Failed to find package " + package.Id + " in catalog " + package.Source.Name); - logger.Close(); + logger.Close(1); return []; } @@ -216,7 +217,7 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa CatalogPackage NativePackage = SearchResult.Result.Matches.First().CatalogPackage; var versions = NativePackage.AvailableVersions.Select(x => x.Version).ToArray(); foreach (var version in versions) logger.Log(version); - logger.Close(); + logger.Close(0); return versions; } @@ -224,7 +225,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc { PackageDetails details = new(package); - var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.GetPackageDetails); + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.LoadPackageDetails); if (package.Source.Name == "winget") details.ManifestUrl = new Uri("https://github.com/microsoft/winget-pkgs/tree/master/manifests/" @@ -240,7 +241,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc if (Catalog == null) { logger.Error("Failed to get catalog " + package.Source.Name + ". Is the package local?"); - logger.Close(); + logger.Close(1); return details; } @@ -250,7 +251,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc if (ConnectResult.Status != Deployment.ConnectResultStatus.Ok) { logger.Error("Failed to connect to catalog " + package.Source.Name); - logger.Close(); + logger.Close(1); return details; } @@ -267,7 +268,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc if (SearchResult.Result == null || SearchResult.Result.Matches == null || SearchResult.Result.Matches.Count() == 0) { logger.Error("WinGet: Failed to find package " + package.Id + " in catalog " + package.Source.Name); - logger.Close(); + logger.Close(1); return details; } @@ -323,6 +324,10 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc process.StartInfo = startInfo; process.Start(); + logger.Log("Begin loading installers:"); + logger.Log(" Executable: " + startInfo.FileName); + logger.Log(" Arguments: " + startInfo.Arguments); + // Retrieve the output string? _line; while ((_line = await process.StandardOutput.ReadLineAsync()) != null) @@ -331,6 +336,9 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc logger.Log(_line); output.Add(_line); } + + logger.Error(await process.StandardError.ReadToEndAsync()); + // Parse the output foreach (string __line in output) { @@ -357,7 +365,7 @@ public async Task GetPackageDetails_UnSafe(WinGet ManagerInstanc Logger.Warn(e.Message); } } - logger.Close(); + logger.Close(0); return details; } } @@ -435,7 +443,7 @@ function Print-WinGetPackage { logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); - logger.Close(); + logger.Close(p.ExitCode); return Packages.ToArray(); @@ -657,7 +665,7 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa } }; - var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.GetPackageVersions, p); + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.LoadPackageVersions, p); p.Start(); @@ -677,7 +685,7 @@ public async Task GetPackageVersions_Unsafe(WinGet ManagerInstance, Pa } logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); - logger.Close(); + logger.Close(p.ExitCode); return versions.ToArray(); } @@ -732,7 +740,7 @@ public async Task GetSources_UnSafe(WinGet ManagerInstance) logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); - logger.Close(); + logger.Close(p.ExitCode); return sources.ToArray(); } diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs index c6f18073b..13f66480c 100644 --- a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs @@ -41,6 +41,10 @@ public abstract class TaskLogger protected IEnumerable? CachedMessage = null; protected IEnumerable? CachedVerboseMessage = null; + const int RETURNCODE_UNSET = -200; + const int RETURNCODE_SUCCESS = 0; + protected int ReturnCode = -200; + public TaskLogger() { StartTime = DateTime.Now; @@ -50,11 +54,12 @@ public TaskLogger() ~TaskLogger() { - if(isOpen) Close(); + if(isOpen) Close(RETURNCODE_UNSET); } - public void Close() + public void Close(int returnCode) { + ReturnCode = returnCode; EndTime = DateTime.Now; isOpen = false; isComplete = true; @@ -68,6 +73,8 @@ public void Close() /// 1. Grey /// 2. Red /// 3. Blue + /// 4. Green + /// 5. Yellow /// /// public abstract IEnumerable AsColoredString(bool verbose = false); @@ -80,7 +87,6 @@ public class ProcessTaskLogger : TaskLogger string Executable; string Arguments; - int ReturnCode; List StdIn = new(); List StdOut = new(); List StdErr = new(); @@ -151,7 +157,7 @@ public override IEnumerable AsColoredString(bool verbose = false) result.Add("0-- Process STDIN"); if(verbose) foreach (var line in StdIn) - result.Add("3" + line); + result.Add("3 " + line); else result.Add("1 ..."); } @@ -161,7 +167,7 @@ public override IEnumerable AsColoredString(bool verbose = false) result.Add("0-- Process STDOUT"); if(verbose) foreach (var line in StdOut) - result.Add("1" + line); + result.Add("1 " + line); else result.Add("1 ..."); } @@ -170,9 +176,14 @@ public override IEnumerable AsColoredString(bool verbose = false) result.Add("0"); result.Add("0-- Process STDERR"); foreach (var line in StdErr) - result.Add("2" + line); + result.Add("2 " + line); } result.Add("0"); + if(!isComplete) result.Add("5Return code: Process has not finished yet"); + else if (ReturnCode == -200) result.Add("5Return code: UNSPECIFIED"); + else if(ReturnCode == 0) result.Add("4Return code: SUCCESS (0)"); + else result.Add($"2Return code: FAILED ({ReturnCode})"); + result.Add("0"); result.Add("0——————————————————————————————————————————"); result.Add("0"); @@ -188,7 +199,6 @@ public class NativeTaskLogger : TaskLogger PackageManager Manager; LoggableTaskType Type; - int ReturnCode; List Info = new(); List Errors = new(); @@ -247,7 +257,7 @@ public override IEnumerable AsColoredString(bool verbose = false) result.Add("0-- Task information"); if (verbose) foreach (var line in Info) - result.Add("1" + line); + result.Add("1 " + line); else result.Add("1 ..."); } @@ -256,9 +266,14 @@ public override IEnumerable AsColoredString(bool verbose = false) result.Add("0"); result.Add("0-- Task errors"); foreach (var line in Errors) - result.Add("2" + line); + result.Add("2 " + line); } result.Add("0"); + if (!isComplete) result.Add("5The task has not finished yet"); + else if (ReturnCode == -200) result.Add("5The task did not report a finish status"); + else if (ReturnCode == 0) result.Add("4The task reported success"); + else result.Add($"2The task reported a failure ({ReturnCode})"); + result.Add("0"); result.Add("0——————————————————————————————————————————"); result.Add("0"); diff --git a/src/UniGetUI/Interface/Pages/LogPage.xaml.cs b/src/UniGetUI/Interface/Pages/LogPage.xaml.cs index 852551299..7ae064cd0 100644 --- a/src/UniGetUI/Interface/Pages/LogPage.xaml.cs +++ b/src/UniGetUI/Interface/Pages/LogPage.xaml.cs @@ -80,22 +80,27 @@ public void SetText(string body) LogTextBox.Blocks.Add(paragraph); } + // Dark theme colors + Color DARK_GREY = Color.FromArgb(255, 130, 130, 130); + Color DARK_LIGHT_GREY = Color.FromArgb(255, 190, 190, 190); + Color DARK_WHITE = Color.FromArgb(255, 250, 250, 250); + Color DARK_YELLOW = Color.FromArgb(255, 255, 255, 90); + Color DARK_RED = Color.FromArgb(255, 255, 80, 80); + Color DARK_GREEN = Color.FromArgb(255, 80, 255, 80); + Color DARK_BLUE = Color.FromArgb(255, 120, 120, 255); + + // Light theme colors + Color LIGHT_GREY = Color.FromArgb(255, 125, 125, 225); + Color LIGHT_LIGHT_GREY = Color.FromArgb(255, 50, 50, 150); + Color LIGHT_WHITE = Color.FromArgb(255, 0, 0, 0); + Color LIGHT_YELLOW = Color.FromArgb(255, 150, 150, 0); + Color LIGHT_RED = Color.FromArgb(255, 205, 0, 0); + Color LIGHT_GREEN = Color.FromArgb(255, 0, 205, 0); + Color LIGHT_BLUE = Color.FromArgb(255, 0, 0, 205); + public void LoadLog() { - // Dark theme colors - Color DARK_GREY = Color.FromArgb(255, 130, 130, 130); - Color DARK_BLUE = Color.FromArgb(255, 190, 190, 190); - Color DARK_WHITE = Color.FromArgb(255, 250, 250, 250); - Color DARK_YELLOW = Color.FromArgb(255, 255, 255, 90); - Color DARK_RED = Color.FromArgb(255, 255, 80, 80); - - // Light theme colors - Color LIGHT_GREY = Color.FromArgb(255, 125, 125, 225); - Color LIGHT_BLUE = Color.FromArgb(255, 50, 50, 150); - Color LIGHT_WHITE = Color.FromArgb(255, 0, 0, 0); - Color LIGHT_YELLOW = Color.FromArgb(255, 150, 150, 0); - Color LIGHT_RED = Color.FromArgb(255, 205, 0, 0); bool IS_DARK = MainApp.Instance.ThemeListener.CurrentTheme == ApplicationTheme.Dark; @@ -125,10 +130,10 @@ public void LoadLog() switch (log_entry.Severity) { case LogEntry.SeverityLevel.Debug: - color = new SolidColorBrush { Color = IS_DARK? DARK_GREY: LIGHT_GREY }; + color = new SolidColorBrush { Color = IS_DARK ? DARK_GREY: LIGHT_GREY }; break; case LogEntry.SeverityLevel.Info: - color = new SolidColorBrush { Color = IS_DARK ? DARK_BLUE : LIGHT_BLUE }; + color = new SolidColorBrush { Color = IS_DARK ? DARK_LIGHT_GREY : LIGHT_LIGHT_GREY }; break; case LogEntry.SeverityLevel.Success: color = new SolidColorBrush { Color = IS_DARK ? DARK_WHITE : LIGHT_WHITE}; @@ -170,6 +175,12 @@ public void LoadLog() { var TaskLogger = manager.TaskLogger; LogTextBox.Blocks.Clear(); + Paragraph versionParagraph = new Paragraph(); + versionParagraph.Inlines.Add(new Run() { Text = $"Manager {manager.Name} with version:\n" }); + versionParagraph.Inlines.Add(new Run() { Text = manager.Status.Version }); + versionParagraph.Inlines.Add(new Run() { Text = $"\n\n——————————————————————————————————————————\n\n" }); + LogTextBox.Blocks.Add(versionParagraph); + foreach (var operation in TaskLogger.Operations) { Paragraph p = new(); @@ -182,7 +193,7 @@ public void LoadLog() color = new SolidColorBrush { Color = IS_DARK ? DARK_WHITE : LIGHT_WHITE}; break; case '1': - color = new SolidColorBrush { Color = IS_DARK ? DARK_GREY : LIGHT_GREY }; + color = new SolidColorBrush { Color = IS_DARK ? DARK_LIGHT_GREY : LIGHT_LIGHT_GREY }; break; case '2': color = new SolidColorBrush { Color = IS_DARK ? DARK_RED : LIGHT_RED }; @@ -190,6 +201,12 @@ public void LoadLog() case '3': color = new SolidColorBrush { Color = IS_DARK ? DARK_BLUE : LIGHT_BLUE }; break; + case '4': + color = new SolidColorBrush { Color = IS_DARK ? DARK_GREEN : LIGHT_GREEN }; + break; + case '5': + color = new SolidColorBrush { Color = IS_DARK ? DARK_YELLOW : LIGHT_YELLOW }; + break; default: color = new SolidColorBrush { Color = IS_DARK ? DARK_YELLOW : LIGHT_YELLOW }; break; From b7e5e0a53c214491c0b94cf4daf5a1d8e721de31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=AD=20Climent?= Date: Sun, 9 Jun 2024 17:18:37 +0200 Subject: [PATCH 5/7] Finish implementing TaskLogger --- src/UniGetUI.PackageEngine.Enums/Enums.cs | 2 +- .../Chocolatey.cs | 20 +-- .../ChocolateySourceProvider.cs | 24 ++- .../DotNet.cs | 147 +++++++----------- .../BaseNuGet.cs | 15 +- .../BaseNuGetDetailsProvider.cs | 13 +- .../Npm.cs | 33 ++-- .../NpmPackageDetailsProvider.cs | 52 ++++--- .../Pip.cs | 87 ++++++----- .../PipPackageDetailsProvider.cs | 55 +++---- .../PowerShell.cs | 32 ++-- .../PowerShellSourceProvider.cs | 27 ++-- .../Scoop.cs | 2 +- .../WinGetHelpers.cs | 6 +- 14 files changed, 266 insertions(+), 249 deletions(-) diff --git a/src/UniGetUI.PackageEngine.Enums/Enums.cs b/src/UniGetUI.PackageEngine.Enums/Enums.cs index f15b6a9f4..08d6f7bbb 100644 --- a/src/UniGetUI.PackageEngine.Enums/Enums.cs +++ b/src/UniGetUI.PackageEngine.Enums/Enums.cs @@ -60,7 +60,7 @@ public enum LoggableTaskType /// /// Searches for packages with a specific query /// - SearchPackages, + FindPackages, /// /// Lists all the available updates /// diff --git a/src/UniGetUI.PackageEngine.Managers.Chocolatey/Chocolatey.cs b/src/UniGetUI.PackageEngine.Managers.Chocolatey/Chocolatey.cs index 77a587baa..6b98f9897 100644 --- a/src/UniGetUI.PackageEngine.Managers.Chocolatey/Chocolatey.cs +++ b/src/UniGetUI.PackageEngine.Managers.Chocolatey/Chocolatey.cs @@ -73,13 +73,14 @@ protected override async Task GetAvailableUpdates_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.ListUpdates, p); p.Start(); + string? line; - string output = ""; List Packages = new(); while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!line.StartsWith("Chocolatey")) { string[] elements = line.Split('|'); @@ -95,10 +96,9 @@ protected override async Task GetAvailableUpdates_UnSafe() } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); - + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + logger.Close(p.ExitCode); return Packages.ToArray(); } @@ -118,13 +118,14 @@ protected override async Task GetInstalledPackages_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.ListPackages, p); p.Start(); + string? line; - string output = ""; List Packages = new(); while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!line.StartsWith("Chocolatey")) { string[] elements = line.Split(' '); @@ -140,10 +141,9 @@ protected override async Task GetInstalledPackages_UnSafe() } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); - + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + logger.Close(p.ExitCode); return Packages.ToArray(); } diff --git a/src/UniGetUI.PackageEngine.Managers.Chocolatey/ChocolateySourceProvider.cs b/src/UniGetUI.PackageEngine.Managers.Chocolatey/ChocolateySourceProvider.cs index 209c613ce..04e825fb3 100644 --- a/src/UniGetUI.PackageEngine.Managers.Chocolatey/ChocolateySourceProvider.cs +++ b/src/UniGetUI.PackageEngine.Managers.Chocolatey/ChocolateySourceProvider.cs @@ -35,8 +35,8 @@ protected override async Task GetSources_UnSafe() { List sources = new(); - Process process = new(); - ProcessStartInfo startInfo = new() + Process p = new(); + p.StartInfo = new() { FileName = Manager.Status.ExecutablePath, Arguments = Manager.Properties.ExecutableCallArgs + " source list", @@ -48,15 +48,13 @@ protected override async Task GetSources_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; - process.StartInfo = startInfo; - process.Start(); + var logger = Manager.TaskLogger.CreateNew(LoggableTaskType.ListSources, p); + p.Start(); - - string output = ""; string? line; - while ((line = await process.StandardOutput.ReadLineAsync()) != null) + while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); try { if (string.IsNullOrEmpty(line)) @@ -73,14 +71,14 @@ protected override async Task GetSources_UnSafe() } catch (Exception e) { - Logger.Error(e); + logger.AddToStdErr(e.ToString()); } } - output += await process.StandardError.ReadToEndAsync(); - Manager.LogOperation(process, output); - - await process.WaitForExitAsync(); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); + return sources.ToArray(); } } diff --git a/src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs b/src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs index ed3e438f4..fc2bb3612 100644 --- a/src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs +++ b/src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs @@ -52,44 +52,49 @@ protected override async Task GetAvailableUpdates_UnSafe() string path = which_res.Item2; if (!which_res.Item1) { - Process proc = new() + Process proc = new Process(); + proc.StartInfo = new ProcessStartInfo() { - StartInfo = new ProcessStartInfo() - { - FileName = path, - Arguments = Properties.ExecutableCallArgs + " install --global dotnet-tools-outdated", - UseShellExecute = true, - CreateNoWindow = true, - } + FileName = path, + Arguments = Properties.ExecutableCallArgs + " install --global dotnet-tools-outdated", + UseShellExecute = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, }; + + var aux_logger = TaskLogger.CreateNew(LoggableTaskType.InstallManagerDependency, proc); proc.Start(); + + aux_logger.AddToStdOut(await proc.StandardOutput.ReadToEndAsync()); + aux_logger.AddToStdErr(await proc.StandardError.ReadToEndAsync()); await proc.WaitForExitAsync(); + aux_logger.Close(proc.ExitCode); + path = "dotnet-tools-outdated.exe"; } - Process p = new() + Process p = new Process(); + p.StartInfo = new ProcessStartInfo() { - StartInfo = new ProcessStartInfo() - { - FileName = path, - Arguments = "", - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 - } + FileName = path, + Arguments = "", + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.ListUpdates, p); p.Start(); string? line; bool DashesPassed = false; List Packages = new(); - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!DashesPassed) { if (line.Contains("----")) @@ -108,96 +113,60 @@ protected override async Task GetAvailableUpdates_UnSafe() Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], elements[2], DefaultSource, this, PackageScope.Global)); } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); return Packages.ToArray(); } protected override async Task GetInstalledPackages_UnSafe() { - Process p = new() - { - StartInfo = new ProcessStartInfo() - { - FileName = Status.ExecutablePath, - Arguments = Properties.ExecutableCallArgs + " list", - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 - } - }; - - p.Start(); - - string? line; - bool DashesPassed = false; List Packages = new(); - while ((line = await p.StandardOutput.ReadLineAsync()) != null) + foreach (var scope in new PackageScope[] { PackageScope.User, PackageScope.Local }) { - if (!DashesPassed) - { - if (line.Contains("----")) - DashesPassed = true; - } - else - { - string[] elements = Regex.Replace(line, " {2,}", " ").Split(' '); - if (elements.Length < 2) - continue; - - for (int i = 0; i < elements.Length; i++) elements[i] = elements[i].Trim(); - if (FALSE_PACKAGE_IDS.Contains(elements[0]) || FALSE_PACKAGE_VERSIONS.Contains(elements[1])) - continue; - - Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], DefaultSource, this, PackageScope.User)); - } - } - - p = new Process() - { - StartInfo = new ProcessStartInfo() + Process p = new Process(); + p.StartInfo = new ProcessStartInfo() { FileName = Status.ExecutablePath, - Arguments = Properties.ExecutableCallArgs + " list --global", + Arguments = Properties.ExecutableCallArgs + $" list" + (scope == PackageScope.Global? "--global": ""), RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, StandardOutputEncoding = System.Text.Encoding.UTF8 - } - }; + }; - p.Start(); + var logger = TaskLogger.CreateNew(LoggableTaskType.ListPackages, p); + p.Start(); - DashesPassed = false; - string output = ""; - while ((line = await p.StandardOutput.ReadLineAsync()) != null) - { - output += line + "\n"; - if (!DashesPassed) + string? line; + bool DashesPassed = false; + while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - if (line.Contains("----")) - DashesPassed = true; - } - else - { - string[] elements = Regex.Replace(line, " {2,}", " ").Split(' '); - if (elements.Length < 2) - continue; + logger.AddToStdOut(line); + if (!DashesPassed) + { + if (line.Contains("----")) + DashesPassed = true; + } + else + { + string[] elements = Regex.Replace(line, " {2,}", " ").Split(' '); + if (elements.Length < 2) + continue; - for (int i = 0; i < elements.Length; i++) elements[i] = elements[i].Trim(); - if (FALSE_PACKAGE_IDS.Contains(elements[0]) || FALSE_PACKAGE_VERSIONS.Contains(elements[1])) - continue; + for (int i = 0; i < elements.Length; i++) elements[i] = elements[i].Trim(); + if (FALSE_PACKAGE_IDS.Contains(elements[0]) || FALSE_PACKAGE_VERSIONS.Contains(elements[1])) + continue; - Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], DefaultSource, this, PackageScope.Global)); + Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], DefaultSource, this, scope)); + } } + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); - return Packages.ToArray(); } diff --git a/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGet.cs b/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGet.cs index 7b989049c..050e96633 100644 --- a/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGet.cs +++ b/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGet.cs @@ -45,16 +45,18 @@ protected sealed override async Task FindPackages_UnSafe(string query { List Packages = new(); + var logger = TaskLogger.CreateNew(Enums.LoggableTaskType.FindPackages); + ManagerSource[] sources; if (Capabilities.SupportsCustomSources) sources = await GetSources(); else - sources = new ManagerSource[] { Properties.DefaultSource }; + sources = [ Properties.DefaultSource ]; foreach(ManagerSource source in sources) { Uri SearchUrl = new($"{source.Url}/Search()?searchTerm=%27{HttpUtility.UrlEncode(query)}%27&targetFramework=%27%27&includePrerelease=false"); - Logger.Debug($"Begin package search with url={SearchUrl} on manager {Name}"); ; + logger.Log($"Begin package search with url={SearchUrl} on manager {Name}"); ; using (HttpClient client = new(CoreData.GenericHttpClientParameters)) { @@ -63,7 +65,7 @@ protected sealed override async Task FindPackages_UnSafe(string query if (!response.IsSuccessStatusCode) { - Logger.Warn($"Failed to fetch api at Url={SearchUrl} with status code {response.StatusCode}"); + logger.Error($"Failed to fetch api at Url={SearchUrl} with status code {response.StatusCode}"); continue; } @@ -86,12 +88,17 @@ protected sealed override async Task FindPackages_UnSafe(string query AlreadyProcessedPackages[id] = new SearchResult { id = id, version = version, version_float = float_version }; } - foreach(SearchResult package in AlreadyProcessedPackages.Values) + foreach (SearchResult package in AlreadyProcessedPackages.Values) + { + logger.Log($"Found package {package.id} version {package.version} on source {source.Name}"); Packages.Add(new Package(CoreTools.FormatAsName(package.id), package.id, package.version, source, this)); + } } } + logger.Close(0); + return Packages.ToArray(); } diff --git a/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGetDetailsProvider.cs b/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGetDetailsProvider.cs index 71cccec7a..60357ec8f 100644 --- a/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGetDetailsProvider.cs +++ b/src/UniGetUI.PackageEngine.Managers.Generic.NuGet/BaseNuGetDetailsProvider.cs @@ -1,5 +1,6 @@ using System.Net; using System.Text.RegularExpressions; +using System.Threading.Tasks.Dataflow; using UniGetUI.Core.Data; using UniGetUI.Core.IconEngine; using UniGetUI.Core.Logging; @@ -8,6 +9,7 @@ using UniGetUI.PackageEngine.ManagerClasses.Manager; using UniGetUI.PackageEngine.Managers.Generic.NuGet.Internal; using UniGetUI.PackageEngine.PackageClasses; +using UniGetUI.PackageEngine.Enums; namespace UniGetUI.PackageEngine.Managers.PowerShellManager { @@ -18,13 +20,18 @@ public BaseNuGetDetailsProvider(BaseNuGet manager) : base(manager) { } protected override async Task GetPackageDetails_Unsafe(Package package) { PackageDetails details = new(package); + var logger = Manager.TaskLogger.CreateNew(LoggableTaskType.LoadPackageDetails); try { + details.ManifestUrl = PackageManifestLoader.GetPackageManifestUrl(package); string? PackageManifestContents = await PackageManifestLoader.GetPackageManifestContent(package); + logger.Log(PackageManifestContents); + if (PackageManifestContents == null) { - Logger.Warn($"No manifest content could be loaded for package {package.Id} on manager {package.Manager.Name}, returning empty PackageDetails"); + logger.Error($"No manifest content could be loaded for package {package.Id} on manager {package.Manager.Name}, returning empty PackageDetails"); + logger.Close(1); return details; } @@ -82,11 +89,13 @@ protected override async Task GetPackageDetails_Unsafe(Package p break; } + logger.Close(0); return details; } catch (Exception e) { - Logger.Error(e); + logger.Error(e); + logger.Close(1); return details; } } diff --git a/src/UniGetUI.PackageEngine.Managers.Npm/Npm.cs b/src/UniGetUI.PackageEngine.Managers.Npm/Npm.cs index ce46ad171..292d71b4b 100644 --- a/src/UniGetUI.PackageEngine.Managers.Npm/Npm.cs +++ b/src/UniGetUI.PackageEngine.Managers.Npm/Npm.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using UniGetUI.Core.Logging; using UniGetUI.Core.Tools; using UniGetUI.PackageEngine.Classes.Manager.ManagerHelpers; using UniGetUI.PackageEngine.Enums; @@ -58,15 +59,17 @@ protected override async Task FindPackages_UnSafe(string query) StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.FindPackages, p); p.Start(); + string? line; List Packages = new(); bool HeaderPassed = false; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!HeaderPassed) + { if (line.Contains("NAME")) HeaderPassed = true; else @@ -75,9 +78,12 @@ protected override async Task FindPackages_UnSafe(string query) if (elements.Length >= 5) Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[4], DefaultSource, this)); } + } } + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + logger.Close(p.ExitCode); return Packages.ToArray(); } @@ -101,12 +107,13 @@ protected override async Task GetAvailableUpdates_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.ListUpdates, p); p.Start(); + string? line; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); string[] elements = line.Split(':'); if (elements.Length >= 4) { @@ -120,10 +127,9 @@ protected override async Task GetAvailableUpdates_UnSafe() } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); - + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + logger.Close(p.ExitCode); } return Packages.ToArray(); } @@ -147,14 +153,15 @@ protected override async Task GetInstalledPackages_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.ListPackages, p); p.Start(); + string? line; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (line.Contains("--") || line.Contains("├─") || line.Contains("└─")) - { + { string[] elements = line[4..].Split('@'); if (elements.Length >= 2) { @@ -163,15 +170,13 @@ protected override async Task GetInstalledPackages_UnSafe() elements[0] = "@" + elements[1]; if (elements.Length >= 3) elements[1] = elements[2]; } - Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], DefaultSource, this, scope)); } } } - - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + logger.Close(p.ExitCode); } return Packages.ToArray(); diff --git a/src/UniGetUI.PackageEngine.Managers.Npm/NpmPackageDetailsProvider.cs b/src/UniGetUI.PackageEngine.Managers.Npm/NpmPackageDetailsProvider.cs index 63c020530..f10d8c117 100644 --- a/src/UniGetUI.PackageEngine.Managers.Npm/NpmPackageDetailsProvider.cs +++ b/src/UniGetUI.PackageEngine.Managers.Npm/NpmPackageDetailsProvider.cs @@ -3,6 +3,7 @@ using UniGetUI.Core.Logging; using UniGetUI.Core.Tools; using UniGetUI.PackageEngine.Classes.Manager.BaseProviders; +using UniGetUI.PackageEngine.ManagerClasses.Classes; using UniGetUI.PackageEngine.ManagerClasses.Manager; using UniGetUI.PackageEngine.PackageClasses; @@ -36,18 +37,13 @@ protected override async Task GetPackageDetails_Unsafe(Package p StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = Manager.TaskLogger.CreateNew(Enums.LoggableTaskType.LoadPackageDetails, p); p.Start(); - List output = new(); - string? line; - while ((line = await p.StandardOutput.ReadLineAsync()) != null) - { - output.Add(line); - } - + string? outLine; int lineNo = 0; bool ReadingMaintainer = false; - foreach (string outLine in output) + while ((outLine = await p.StandardOutput.ReadLineAsync()) != null) { try { @@ -90,9 +86,13 @@ protected override async Task GetPackageDetails_Unsafe(Package p } catch (Exception e) { - Logger.Warn(e); + logger.AddToStdErr(e.ToString()); } } + + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); } } catch (Exception e) @@ -115,33 +115,37 @@ protected override Task GetPackageScreenshots_Unsafe(Package package) protected override async Task GetPackageVersions_Unsafe(Package package) { - Process p = new() + Process p = new Process(); + p.StartInfo = new ProcessStartInfo() { - StartInfo = new ProcessStartInfo() - { - FileName = Manager.Status.ExecutablePath, - Arguments = Manager.Properties.ExecutableCallArgs + " show " + package.Id + " versions --json", - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - RedirectStandardInput = true, - CreateNoWindow = true, - WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), - StandardOutputEncoding = System.Text.Encoding.UTF8 - } + FileName = Manager.Status.ExecutablePath, + Arguments = Manager.Properties.ExecutableCallArgs + " show " + package.Id + " versions --json", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = true, + CreateNoWindow = true, + WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = Manager.TaskLogger.CreateNew(Enums.LoggableTaskType.LoadPackageVersions, p); + p.Start(); + string? line; List versions = new(); - p.Start(); - while ((line = await p.StandardOutput.ReadLineAsync()) != null) { + logger.AddToStdOut(line); if (line.Contains("\"")) versions.Add(line.Trim().TrimStart('"').TrimEnd(',').TrimEnd('"')); } + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); + return versions.ToArray(); } } diff --git a/src/UniGetUI.PackageEngine.Managers.Pip/Pip.cs b/src/UniGetUI.PackageEngine.Managers.Pip/Pip.cs index 1da75a97e..b644eb8fb 100644 --- a/src/UniGetUI.PackageEngine.Managers.Pip/Pip.cs +++ b/src/UniGetUI.PackageEngine.Managers.Pip/Pip.cs @@ -1,8 +1,10 @@ using System.Diagnostics; using System.Text.RegularExpressions; +using UniGetUI.Core.Logging; using UniGetUI.Core.Tools; using UniGetUI.PackageEngine.Classes.Manager.ManagerHelpers; using UniGetUI.PackageEngine.Enums; +using UniGetUI.PackageEngine.ManagerClasses.Classes; using UniGetUI.PackageEngine.ManagerClasses.Manager; using UniGetUI.PackageEngine.PackageClasses; @@ -47,10 +49,10 @@ protected override async Task FindPackages_UnSafe(string query) { List Packages = new(); - Tuple which_res = await CoreTools.Which("parse_pip_search"); + Tuple which_res = await CoreTools.Which("parse_pip_search.exe"); string path = which_res.Item2; if (!which_res.Item1) - { + { Process proc = new() { StartInfo = new ProcessStartInfo() @@ -58,11 +60,19 @@ protected override async Task FindPackages_UnSafe(string query) FileName = path, Arguments = Properties.ExecutableCallArgs + " install parse_pip_search", UseShellExecute = true, + RedirectStandardOutput = true, + RedirectStandardError = true, CreateNoWindow = true, } }; + var aux_logger = TaskLogger.CreateNew(LoggableTaskType.InstallManagerDependency, proc); proc.Start(); + + aux_logger.AddToStdOut(await proc.StandardOutput.ReadToEndAsync()); + aux_logger.AddToStdErr(await proc.StandardError.ReadToEndAsync()); + await proc.WaitForExitAsync(); + aux_logger.Close(proc.ExitCode); path = "parse_pip_search.exe"; } @@ -80,14 +90,15 @@ protected override async Task FindPackages_UnSafe(string query) } }; + var logger = TaskLogger.CreateNew(LoggableTaskType.FindPackages, p); + p.Start(); string? line; bool DashesPassed = false; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!DashesPassed) { if (line.Contains("----")) @@ -106,36 +117,37 @@ protected override async Task FindPackages_UnSafe(string query) Packages.Add(new Package(Core.Tools.CoreTools.FormatAsName(elements[0]), elements[0], elements[1], DefaultSource, this, scope: PackageScope.Global)); } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); + return Packages.ToArray(); } protected override async Task GetAvailableUpdates_UnSafe() { - Process p = new() + Process p = new Process(); + p.StartInfo = new ProcessStartInfo() { - StartInfo = new ProcessStartInfo() - { - FileName = Status.ExecutablePath, - Arguments = Properties.ExecutableCallArgs + " list --outdated", - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 - } + FileName = Status.ExecutablePath, + Arguments = Properties.ExecutableCallArgs + " list --outdated", + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.ListUpdates, p); + p.Start(); string? line; bool DashesPassed = false; List Packages = new(); - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!DashesPassed) { if (line.Contains("----")) @@ -154,37 +166,38 @@ protected override async Task GetAvailableUpdates_UnSafe() Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], elements[2], DefaultSource, this, scope: PackageScope.Global)); } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); + return Packages.ToArray(); } protected override async Task GetInstalledPackages_UnSafe() { - Process p = new() + Process p = new Process(); + p.StartInfo = new ProcessStartInfo() { - StartInfo = new ProcessStartInfo() - { - FileName = Status.ExecutablePath, - Arguments = Properties.ExecutableCallArgs + " list", - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 - } + FileName = Status.ExecutablePath, + Arguments = Properties.ExecutableCallArgs + " list", + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + StandardOutputEncoding = System.Text.Encoding.UTF8 }; + + var logger = TaskLogger.CreateNew(LoggableTaskType.ListPackages, p); p.Start(); string? line; bool DashesPassed = false; List Packages = new(); - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!DashesPassed) { if (line.Contains("----")) @@ -203,8 +216,10 @@ protected override async Task GetInstalledPackages_UnSafe() Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], DefaultSource, this, scope: PackageScope.Global)); } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); + return Packages.ToArray(); } diff --git a/src/UniGetUI.PackageEngine.Managers.Pip/PipPackageDetailsProvider.cs b/src/UniGetUI.PackageEngine.Managers.Pip/PipPackageDetailsProvider.cs index 1c3dd57dd..4e15cc6ad 100644 --- a/src/UniGetUI.PackageEngine.Managers.Pip/PipPackageDetailsProvider.cs +++ b/src/UniGetUI.PackageEngine.Managers.Pip/PipPackageDetailsProvider.cs @@ -18,6 +18,7 @@ protected override async Task GetPackageDetails_Unsafe(Package p { PackageDetails details = new(package); + var logger = Manager.TaskLogger.CreateNew(Enums.LoggableTaskType.LoadPackageDetails); string JsonString; HttpClient client = new(CoreData.GenericHttpClientParameters); @@ -28,7 +29,8 @@ protected override async Task GetPackageDetails_Unsafe(Package p if(RawInfo == null) { - Logger.Error($"Can't load package info on manager {Manager.Name}, JsonObject? RawInfo was null"); + logger.Error($"Can't load package info on manager {Manager.Name}, JsonObject? RawInfo was null"); + logger.Close(1); return details; } @@ -40,37 +42,37 @@ protected override async Task GetPackageDetails_Unsafe(Package p if (infoNode.ContainsKey("author")) details.Author = CoreTools.GetStringOrNull(infoNode["author"]?.ToString()); } - catch (Exception ex) { Logger.Debug("[Pip] Can't load author: " + ex); } + catch (Exception ex) { logger.Error("Can't load author: " + ex); } try { if (infoNode.ContainsKey("home_page")) details.HomepageUrl = CoreTools.GetUriOrNull(infoNode["home_page"]?.ToString()); } - catch (Exception ex) { Logger.Debug("[Pip] Can't load home_page: " + ex); } + catch (Exception ex) { logger.Error("Can't load home_page: " + ex); } try { if (infoNode.ContainsKey("package_url")) details.ManifestUrl = CoreTools.GetUriOrNull(infoNode["package_url"]?.ToString()); } - catch (Exception ex) { Logger.Debug("[Pip] Can't load package_url: " + ex); } + catch (Exception ex) { logger.Error("Can't load package_url: " + ex); } try { if (infoNode.ContainsKey("summary")) details.Description = CoreTools.GetStringOrNull(infoNode["summary"]?.ToString()); } - catch (Exception ex) { Logger.Debug("[Pip] Can't load summary: " + ex); } + catch (Exception ex) { logger.Error("Can't load summary: " + ex); } try { if (infoNode.ContainsKey("license")) details.License = CoreTools.GetStringOrNull(infoNode["license"]?.ToString()); } - catch (Exception ex) { Logger.Debug("[Pip] Can't load license: " + ex); } + catch (Exception ex) { logger.Error("Can't load license: " + ex); } try { if (infoNode.ContainsKey("maintainer")) details.Publisher = CoreTools.GetStringOrNull(infoNode["maintainer"]?.ToString()); } - catch (Exception ex) { Logger.Debug("[Pip] Can't load maintainer: " + ex); } + catch (Exception ex) { logger.Error("Can't load maintainer: " + ex); } try { if ((infoNode.ContainsKey("classifiers")) @@ -86,7 +88,7 @@ protected override async Task GetPackageDetails_Unsafe(Package p details.Tags = Tags.ToArray(); } } - catch (Exception ex) { Logger.Debug("[Pip] Can't load classifiers: " + ex); } + catch (Exception ex) { logger.Error("Can't load classifiers: " + ex); } } try @@ -112,8 +114,9 @@ protected override async Task GetPackageDetails_Unsafe(Package p } } } - catch (Exception ex) { Logger.Debug("Can't load installer data: " + ex); } + catch (Exception ex) { logger.Error("Can't load installer data: " + ex); } + logger.Close(0); return details; } @@ -129,35 +132,35 @@ protected override Task GetPackageScreenshots_Unsafe(Package package) protected override async Task GetPackageVersions_Unsafe(Package package) { - Process p = new() + Process p = new Process(); + p.StartInfo = new ProcessStartInfo() { - StartInfo = new ProcessStartInfo() - { - FileName = Manager.Status.ExecutablePath, - Arguments = Manager.Properties.ExecutableCallArgs + " index versions " + package.Id, - RedirectStandardOutput = true, - RedirectStandardInput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true, - StandardOutputEncoding = System.Text.Encoding.UTF8 - } + FileName = Manager.Status.ExecutablePath, + Arguments = Manager.Properties.ExecutableCallArgs + " index versions " + package.Id, + RedirectStandardOutput = true, + RedirectStandardInput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = Manager.TaskLogger.CreateNew(Enums.LoggableTaskType.LoadPackageVersions, p); p.Start(); string? line; - string[] result = new string[0]; - string output = ""; + string[] result = []; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (line.Contains("Available versions:")) result = line.Replace("Available versions:", "").Trim().Split(", "); } - output += await p.StandardError.ReadToEndAsync(); - Manager.LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); + return result; } } diff --git a/src/UniGetUI.PackageEngine.Managers.PowerShell/PowerShell.cs b/src/UniGetUI.PackageEngine.Managers.PowerShell/PowerShell.cs index 725750400..3f32c594a 100644 --- a/src/UniGetUI.PackageEngine.Managers.PowerShell/PowerShell.cs +++ b/src/UniGetUI.PackageEngine.Managers.PowerShell/PowerShell.cs @@ -3,6 +3,7 @@ using UniGetUI.Core.Tools; using UniGetUI.PackageEngine.Classes.Manager.ManagerHelpers; using UniGetUI.PackageEngine.Enums; +using UniGetUI.PackageEngine.ManagerClasses.Classes; using UniGetUI.PackageEngine.ManagerClasses.Manager; using UniGetUI.PackageEngine.PackageClasses; @@ -65,9 +66,11 @@ protected override async Task GetAvailableUpdates_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.ListUpdates, p); + p.Start(); - await p.StandardInput.WriteLineAsync(@" + string command = """ function Test-GalleryModuleUpdate { param ( [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [string] $Name, @@ -78,24 +81,26 @@ function Test-GalleryModuleUpdate { process { $URLs = @{} @(Get-PSRepository).ForEach({$URLs[$_.Name] = $_.SourceLocation}) - $page = Invoke-WebRequest -Uri ($URLs[$Repository] + ""/package/$Name"") -UseBasicParsing -Maximum 0 -ea Ignore - [version]$latest = Split-Path -Path ($page.Headers.Location -replace ""$Name."" -replace "".nupkg"") -Leaf + $page = Invoke-WebRequest -Uri ($URLs[$Repository] + "/package/$Name") -UseBasicParsing -Maximum 0 -ea Ignore + [version]$latest = Split-Path -Path ($page.Headers.Location -replace "$Name." -replace ".nupkg") -Leaf $needsupdate = $Latest -gt $Version if ($needsupdate) { - Write-Output($Name + ""|"" + $Version.ToString() + ""|"" + $Latest.ToString() + ""|"" + $Repository) + Write-Output($Name + "|" + $Version.ToString() + "|" + $Latest.ToString() + "|" + $Repository) } } } Get-InstalledModule | Test-GalleryModuleUpdate exit - "); // do NOT remove the trailing endline + """; + await p.StandardInput.WriteLineAsync(command); + logger.AddToStdIn(command); + string? line; List Packages = new(); - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (line.StartsWith(">>")) continue; @@ -111,9 +116,9 @@ function Test-GalleryModuleUpdate { Packages.Add(new Package(CoreTools.FormatAsName(elements[0]), elements[0], elements[1], elements[2], GetSourceOrDefault(elements[3]), this)); } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + logger.Close(p.ExitCode); return Packages.ToArray(); } @@ -133,14 +138,15 @@ protected override async Task GetInstalledPackages_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; + var logger = TaskLogger.CreateNew(LoggableTaskType.ListPackages, p); + p.Start(); string? line; List Packages = new(); bool DashesPassed = false; - string output = ""; while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); if (!DashesPassed) { if (line.Contains("-----")) @@ -158,9 +164,9 @@ protected override async Task GetInstalledPackages_UnSafe() } } - output += await p.StandardError.ReadToEndAsync(); - LogOperation(p, output); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); await p.WaitForExitAsync(); + logger.Close(p.ExitCode); return Packages.ToArray(); } diff --git a/src/UniGetUI.PackageEngine.Managers.PowerShell/PowerShellSourceProvider.cs b/src/UniGetUI.PackageEngine.Managers.PowerShell/PowerShellSourceProvider.cs index a501d9de4..d24bb8780 100644 --- a/src/UniGetUI.PackageEngine.Managers.PowerShell/PowerShellSourceProvider.cs +++ b/src/UniGetUI.PackageEngine.Managers.PowerShell/PowerShellSourceProvider.cs @@ -15,13 +15,13 @@ public PowerShellSourceProvider(PowerShell manager) : base(manager) { } public override string[] GetAddSourceParameters(ManagerSource source) { if (source.Url.ToString() == "https://www.powershellgallery.com/api/v2") - return new string[] { "Register-PSRepository", "-Default" }; - return new string[] { "Register-PSRepository", "-Name", source.Name, "-SourceLocation", source.Url.ToString() }; + return [ "Register-PSRepository", "-Default" ]; + return [ "Register-PSRepository", "-Name", source.Name, "-SourceLocation", source.Url.ToString() ]; } public override string[] GetRemoveSourceParameters(ManagerSource source) { - return new string[] { "Unregister-PSRepository", "-Name", source.Name }; + return [ "Unregister-PSRepository", "-Name", source.Name ]; } public override OperationVeredict GetAddSourceOperationVeredict(ManagerSource source, int ReturnCode, string[] Output) @@ -38,8 +38,8 @@ protected override async Task GetSources_UnSafe() { List sources = new(); - Process process = new(); - ProcessStartInfo startInfo = new() + Process p = new(); + p.StartInfo = new() { FileName = Manager.Status.ExecutablePath, Arguments = Manager.Properties.ExecutableCallArgs + " Get-PSRepository", @@ -51,15 +51,15 @@ protected override async Task GetSources_UnSafe() StandardOutputEncoding = System.Text.Encoding.UTF8 }; - process.StartInfo = startInfo; - process.Start(); + var logger = Manager.TaskLogger.CreateNew(LoggableTaskType.ListSources, p); + + p.Start(); bool dashesPassed = false; string? line; - string output = ""; - while ((line = await process.StandardOutput.ReadLineAsync()) != null) + while ((line = await p.StandardOutput.ReadLineAsync()) != null) { - output += line + "\n"; + logger.AddToStdOut(line); try { if (string.IsNullOrEmpty(line)) @@ -82,9 +82,10 @@ protected override async Task GetSources_UnSafe() Logger.Warn(e); } } - output += await process.StandardError.ReadToEndAsync(); - Manager.LogOperation(process, output); - await process.WaitForExitAsync(); + logger.AddToStdErr(await p.StandardError.ReadToEndAsync()); + await p.WaitForExitAsync(); + logger.Close(p.ExitCode); + return sources.ToArray(); } } diff --git a/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs b/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs index 445491d77..4afc458e0 100644 --- a/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs +++ b/src/UniGetUI.PackageEngine.Managers.Scoop/Scoop.cs @@ -108,7 +108,7 @@ protected override async Task FindPackages_UnSafe(string query) StandardOutputEncoding = System.Text.Encoding.UTF8 } }; - var logger = TaskLogger.CreateNew(LoggableTaskType.SearchPackages, p); + var logger = TaskLogger.CreateNew(LoggableTaskType.FindPackages, p); p.Start(); diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs index 9c9b427bf..3719612ec 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs @@ -59,7 +59,7 @@ public NativeWinGetHelper() public async Task FindPackages_UnSafe(WinGet ManagerInstance, string query) { - var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.SearchPackages); + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.FindPackages); List Packages = new(); FindPackagesOptions PackageFilters = Factory.CreateFindPackagesOptions(); @@ -398,7 +398,7 @@ public async Task FindPackages_UnSafe(WinGet ManagerInstance, string p.Start(); - var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.SearchPackages, p); + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.FindPackages, p); var command = """ Set-ExecutionPolicy Bypass -Scope Process -Force @@ -708,7 +708,7 @@ public async Task GetSources_UnSafe(WinGet ManagerInstance) p.Start(); - var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.SearchPackages, p); + var logger = ManagerInstance.TaskLogger.CreateNew(LoggableTaskType.FindPackages, p); bool dashesPassed = false; string? line; From 16f0dcab1141e98f99a944bf776134a4ab4d6435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=AD=20Climent?= Date: Sun, 9 Jun 2024 17:24:18 +0200 Subject: [PATCH 6/7] Fixes to .NET Tool --- src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs | 2 +- src/UniGetUI/Interface/Pages/LogPage.xaml.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs b/src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs index fc2bb3612..85da871fb 100644 --- a/src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs +++ b/src/UniGetUI.PackageEngine.Managers.Dotnet/DotNet.cs @@ -123,7 +123,7 @@ protected override async Task GetAvailableUpdates_UnSafe() protected override async Task GetInstalledPackages_UnSafe() { List Packages = new(); - foreach (var scope in new PackageScope[] { PackageScope.User, PackageScope.Local }) + foreach (var scope in new PackageScope[] { PackageScope.Local, PackageScope.Global}) { Process p = new Process(); p.StartInfo = new ProcessStartInfo() diff --git a/src/UniGetUI/Interface/Pages/LogPage.xaml.cs b/src/UniGetUI/Interface/Pages/LogPage.xaml.cs index 7ae064cd0..10b06c8ab 100644 --- a/src/UniGetUI/Interface/Pages/LogPage.xaml.cs +++ b/src/UniGetUI/Interface/Pages/LogPage.xaml.cs @@ -171,7 +171,7 @@ public void LoadLog() { bool verbose = LogLevelCombo.SelectedValue?.ToString()?.Contains("(") ?? false; foreach (var manager in MainApp.Instance.PackageManagerList) - if (manager.Name == LogLevelCombo.SelectedValue?.ToString()?.Split(' ')[0]) + if (manager.Name.Contains(LogLevelCombo.SelectedValue?.ToString()?.Split(' ')[0] ?? "uncontained_word")) { var TaskLogger = manager.TaskLogger; LogTextBox.Blocks.Clear(); From 1a2caef978951bc038a1c73645f6650d75072458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=AD=20Climent?= Date: Sun, 9 Jun 2024 17:26:22 +0200 Subject: [PATCH 7/7] Update WinGetHelpers.cs --- src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs index 3719612ec..99460b630 100644 --- a/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs +++ b/src/UniGetUI.PackageEngine.Managers.WinGet/WinGetHelpers.cs @@ -163,13 +163,12 @@ public async Task GetSources_UnSafe(WinGet ManagerInstance) { logger.Log($"Found source {catalog.Info.Name} with argument {catalog.Info.Argument}"); sources.Add(new ManagerSource(ManagerInstance, catalog.Info.Name, new Uri(catalog.Info.Argument), updateDate: catalog.Info.LastUpdateTime.ToString())); - logger.Close(0); } catch (Exception e) { logger.Error(e); - logger.Close(1); } + logger.Close(0); return sources.ToArray(); }