Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove PowerShell Module parsing support #2782

Merged
merged 4 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 25 additions & 25 deletions InstallerExtras/EnsureWinGet.ps1
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
Set-ExecutionPolicy Bypass -Scope Process -Force
if (!(Get-Command -Verb Repair -Noun WinGetPackageManager)) {
Write-Output "Microsoft.WinGet.Client is not installed or is not on the latest version"
try
{
Write-Output "Attempting to uninstall an older version of Microsoft.WinGet.Client..."
Uninstall-Module -Name Microsoft.WinGet.Client -Confirm:$false -Force -Scope CurrentUser
if ($null -eq (Get-Command "winget.exe" -ErrorAction SilentlyContinue))
{
Write-Output "WinGet is not present on the system"
if (!(Get-Command -Verb Repair -Noun WinGetPackageManager)) {
Write-Output "Microsoft.WinGet.Client is not installed or is not on the latest version"
try
{
Write-Output "Attempting to uninstall an older version of Microsoft.WinGet.Client..."
Uninstall-Module -Name Microsoft.WinGet.Client -Confirm:$false -Force -Scope CurrentUser
}
catch
{
Write-Output "Microsoft.WinGet.Client was not installed."
}
Write-Output "Installing Microsoft.WinGet.Client..."
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false -Scope CurrentUser
Install-Module -Name Microsoft.WinGet.Client -Confirm:$false -Force -Scope CurrentUser
Write-Output "Microsoft.WinGet.Client was installed successfully"
}
catch

Write-Output "Checking for updates for Microsoft.WinGet.Client module..."
if ((Get-Module -Name Microsoft.WinGet.Client -ListAvailable).Version -ge '1.8.1791')
{
Write-Output "Microsoft.WinGet.Client was not installed."
Write-Output "Microsoft.WinGet.Client is up-to-date"
} else {
Write-Output "Updating Microsoft.WinGet.Client module..."
Update-Module -Name Microsoft.WinGet.Client -Confirm:$false -Force -Scope CurrentUser
}
Write-Output "Installing Microsoft.WinGet.Client..."
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false -Scope CurrentUser
Install-Module -Name Microsoft.WinGet.Client -Confirm:$false -Force -Scope CurrentUser
Write-Output "Microsoft.WinGet.Client was installed successfully"
}

Write-Output "Checking for updates for Microsoft.WinGet.Client module..."
if ((Get-Module -Name Microsoft.WinGet.Client -ListAvailable).Version -ge '1.8.1791')
{
Write-Output "Microsoft.WinGet.Client is up-to-date"
} else {
Write-Output "Updating Microsoft.WinGet.Client module..."
Update-Module -Name Microsoft.WinGet.Client -Confirm:$false -Force -Scope CurrentUser
}

if ($null -eq (Get-Command "winget.exe" -ErrorAction SilentlyContinue))
{
Write-Output "WinGet is not present on the system"
Write-Output "Installing WinGet..."
Repair-WinGetPackageManager
Write-Output "WinGet was installed successfully"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ protected override IEnumerable<string> GetInstallableVersions_UnSafe(IPackage pa
{
StartInfo = new ProcessStartInfo
{
// choco search php --exact --all-versions
FileName = Manager.Status.ExecutablePath,
Arguments = Manager.Properties.ExecutableCallArgs + $" search {package.Id} --exact --all-versions",
UseShellExecute = false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@
namespace UniGetUI.PackageEngine.Managers.WingetManager;
internal sealed class WinGetOperationProvider : BaseOperationProvider<WinGet>
{
public static string GetIdNamePiece(IPackage package)
{
if(!package.Id.EndsWith("…"))
return $"--id \"{package.Id.TrimEnd('…')}\" --exact";

if (!package.Name.EndsWith("…"))
return $"--name \"{package.Name}\" --exact";

return $"--id \"{package.Id.TrimEnd('…')}\"";
}

public WinGetOperationProvider(WinGet manager) : base(manager) { }

public override IEnumerable<string> GetOperationParameters(IPackage package, IInstallationOptions options, OperationType operation)
Expand All @@ -17,7 +28,8 @@ public override IEnumerable<string> GetOperationParameters(IPackage package, IIn
OperationType.Uninstall => Manager.Properties.UninstallVerb,
_ => throw new InvalidDataException("Invalid package operation")
}];
parameters.AddRange(["--id", $"\"{package.Id}\"", "--exact"]);

parameters.AddRange(GetIdNamePiece(package).Split(" "));
parameters.AddRange(["--source", package.Source.IsVirtualManager ? "winget" : package.Source.Name]);
parameters.AddRange(["--accept-source-agreements", "--disable-interactivity"]);

Expand Down
80 changes: 11 additions & 69 deletions src/UniGetUI.PackageEngine.Managers.WinGet/WinGet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,51 +28,12 @@ public class WinGet : PackageManager
public LocalWinGetSource GOGSource { get; }
public LocalWinGetSource MicrosoftStoreSource { get; }

public readonly string PowerShellPath;
public readonly string PowerShellPromptArgs;
public readonly string PowerShellInlineArgs;
public string WinGetBundledPath;

public WinGet()
{
PowerShellPath = Path.Join(Environment.SystemDirectory, "windowspowershell\\v1.0\\powershell.exe");
PowerShellPromptArgs = "-ExecutionPolicy Bypass -NoLogo -NoProfile";
PowerShellInlineArgs = "-ExecutionPolicy Bypass -NoLogo -NoProfile -NonInteractive";

WinGetBundledPath = Path.Join(CoreData.UniGetUIExecutableDirectory, "winget-cli_x64", "winget.exe");

Dependencies = [
new ManagerDependency(
"WinGet PowerShell Module",
PowerShellPath,
PowerShellPromptArgs + " -Command \"& {Install-Module -Name Microsoft.WinGet.Client -Force -Confirm:$false -Scope CurrentUser; if($error.count -ne 0){pause}}\"",
"Install-Module -Name Microsoft.WinGet.Client -Scope CurrentUser",
async () =>
{
if (!Settings.Get("ForceUsePowerShellModules") || Settings.Get("ForceLegacyBundledWinGet"))
{
Logger.ImportantInfo("Microsoft.Powershell.Client detection has been forcefully skipped as the module is not required on the current context");
return true;
}

Process p = new()
{
StartInfo = new ProcessStartInfo
{
FileName = PowerShellPath,
Arguments = PowerShellPromptArgs,
RedirectStandardInput = true,
CreateNoWindow = true
},
};
p.Start();
await p.StandardInput.WriteAsync("if(Get-Module -ListAvailable -Name \"Microsoft.WinGet.Client\"){exit 0}Else{exit 1}");
p.StandardInput.Close();
await p.WaitForExitAsync();
return p.ExitCode == 0;
})
];

Capabilities = new ManagerCapabilities
{
CanRunAsAdmin = true,
Expand Down Expand Up @@ -156,7 +117,7 @@ public ManagerSource GetLocalSource(string id)
}

// Check if source is android
if(MeaningfulId.Count(x => x == '.') >= 2 && MeaningfulId.All(c => (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.'))
if(MeaningfulId.Count(x => x == '.') >= 2 && MeaningfulId.All(c => (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '…'))
{
return AndroidSubsystemSource;
}
Expand Down Expand Up @@ -197,7 +158,7 @@ protected override ManagerStatus LoadManager()

if (!status.Found)
{
Logger.Error("User does not have WinGet installed");
Logger.Error("User does not have WinGet installed, forcing bundled WinGet...");
FORCE_BUNDLED = true;
}

Expand Down Expand Up @@ -234,45 +195,26 @@ protected override ManagerStatus LoadManager()
Logger.Error("WinGet STDERR not empty: " + error);
}

process = new()
{
StartInfo = new ProcessStartInfo
{
FileName = PowerShellPath,
Arguments = PowerShellInlineArgs + " -Command Write-Output (Get-Module -Name Microsoft.WinGet.Client).Version",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
StandardOutputEncoding = System.Text.Encoding.UTF8,
StandardErrorEncoding = System.Text.Encoding.UTF8
}
};
process.Start();
status.Version += $"\nMicrosoft.WinGet.Client PSModule version: \"{process.StandardOutput.ReadToEnd().Trim()}\"";
error = process.StandardError.ReadToEnd();
if (error != "")
{
Logger.Error("WinGet STDERR not empty: " + error);
}

try
{
if (FORCE_BUNDLED)
{
throw new InvalidOperationException("Bundled WinGet was forced by the user!");
WinGetHelper.Instance = new BundledWinGetHelper();
status.Version += "\nUsing bundled WinGet helper (CLI parsing)";
}
else
{
WinGetHelper.Instance = new NativeWinGetHelper();
status.Version += "\nUsing Native WinGet helper (COM Api)";
}

WinGetHelper.Instance = new NativeWinGetHelper();
status.Version += "\nUsing Native WinGet helper (COM Api)";
}
catch (Exception ex)
{
Logger.Warn($"Cannot create native WinGet instance due to error: {ex.Message}");
Logger.Warn($"Cannot instantiate {(FORCE_BUNDLED? "Bundled" : "Native")} WinGet Helper due to error: {ex.Message}");
Logger.Warn(ex);
Logger.Warn("WinGet will resort to using BundledWinGetHelper()");
WinGetHelper.Instance = new BundledWinGetHelper();
status.Version += "\nUsing bundled WinGet helper (CLI parsing)";
status.Version += "\nUsing bundled WinGet helper (CLI parsing, caused by exception)";
}

return status;
Expand Down
Loading
Loading