Skip to content

Commit 1a012ce

Browse files
committed
(#2886) Switch remembered args to only change local configuration
This adds a new method, GetPackageConfigFromRememberedArguments which is similar to SetConfigFromRememberedArguments, but operates using a different method. First, a OptionSet is set up, so only the config that is passed in is modified, instead of the config that the global options parser was set with with. Second, it returns the modified configuration instead of the original configuration, because it is the local configuration being modified. Third, it has a more general name and changes log messages to be more general, so it later can more easily be reused for uninstall and export. This change fixes remembered arguments when Chocolatey is used as a library, like in ChocolateyGUI, where the config that is passed to the install_run method is not necessarily the same config object that was used to set up the global argument parser. The downside of using a new commandline parser is that it opens up the possibility of drift between the upgrade/global arguments and this added parser. However, this is not an issue because the format of the saved arguments is known, and any added arguments there would not work without being added here as well, which would be picked up during development.
1 parent d23fc36 commit 1a012ce

File tree

2 files changed

+139
-8
lines changed

2 files changed

+139
-8
lines changed

src/chocolatey/infrastructure.app/services/INugetService.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ namespace chocolatey.infrastructure.app.services
2020
using System.Collections.Concurrent;
2121
using System.Collections.Generic;
2222
using configuration;
23+
using domain;
2324
using results;
2425

2526
public interface INugetService : ISourceRunner
@@ -67,6 +68,15 @@ public interface INugetService : ISourceRunner
6768
/// <param name="config">The configuration</param>
6869
IEnumerable<PackageResult> GetInstalledPackages(ChocolateyConfiguration config);
6970

71+
/// <summary>
72+
/// Gets the configuration from remembered arguments
73+
/// </summary>
74+
/// <param name="config">The original configuration.</param>
75+
/// <param name="packageInfo">The package information.</param>
76+
/// <returns>The modified configuration, so it can be used</returns>
77+
ChocolateyConfiguration GetPackageConfigFromRememberedArguments(ChocolateyConfiguration config,
78+
ChocolateyPackageInformation packageInfo);
79+
7080
#pragma warning disable IDE1006
7181
[Obsolete("This overload is deprecated and will be removed in v3.")]
7282
ConcurrentDictionary<string, PackageResult> get_outdated(ChocolateyConfiguration config);

src/chocolatey/infrastructure.app/services/NugetService.cs

Lines changed: 129 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1050,7 +1050,7 @@ public virtual ConcurrentDictionary<string, PackageResult> Upgrade(ChocolateyCon
10501050
continue;
10511051
}
10521052

1053-
SetConfigFromRememberedArguments(config, pkgInfo);
1053+
config = GetPackageConfigFromRememberedArguments(config, pkgInfo);
10541054
var pathResolver = NugetCommon.GetPathResolver(_fileSystem);
10551055
var nugetProject = new FolderNuGetProject(ApplicationParameters.PackagesLocation, pathResolver, NuGetFramework.AnyFramework);
10561056

@@ -1658,12 +1658,7 @@ public virtual ConcurrentDictionary<string, PackageResult> GetOutdated(Chocolate
16581658
return outdatedPackages;
16591659
}
16601660

1661-
/// <summary>
1662-
/// Sets the configuration for the package upgrade
1663-
/// </summary>
1664-
/// <param name="config">The configuration.</param>
1665-
/// <param name="packageInfo">The package information.</param>
1666-
/// <returns>The original unmodified configuration, so it can be reset after upgrade</returns>
1661+
[Obsolete("This method is deprecated and will be removed in v3.")]
16671662
protected virtual ChocolateyConfiguration SetConfigFromRememberedArguments(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo)
16681663
{
16691664
if (!config.Features.UseRememberedArgumentsForUpgrades || string.IsNullOrWhiteSpace(packageInfo.Arguments)) return config;
@@ -1708,7 +1703,7 @@ protected virtual ChocolateyConfiguration SetConfigFromRememberedArguments(Choco
17081703
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.Password)) config.SourceCommand.Password = originalConfig.SourceCommand.Password;
17091704
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.Certificate)) config.SourceCommand.Certificate = originalConfig.SourceCommand.Certificate;
17101705
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.CertificatePassword)) config.SourceCommand.CertificatePassword = originalConfig.SourceCommand.CertificatePassword;
1711-
1706+
17121707
if (originalConfig.CacheLocationArgumentWasPassed && !string.IsNullOrWhiteSpace(originalConfig.CacheLocation))
17131708
{
17141709
config.CacheLocation = originalConfig.CacheLocation;
@@ -1722,6 +1717,132 @@ protected virtual ChocolateyConfiguration SetConfigFromRememberedArguments(Choco
17221717
return originalConfig;
17231718
}
17241719

1720+
/// <summary>
1721+
/// Gets the configuration from remembered arguments
1722+
/// </summary>
1723+
/// <param name="config">The original configuration.</param>
1724+
/// <param name="packageInfo">The package information.</param>
1725+
/// <returns>The modified configuration, so it can be used</returns>
1726+
public virtual ChocolateyConfiguration GetPackageConfigFromRememberedArguments(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo)
1727+
{
1728+
if (!config.Features.UseRememberedArgumentsForUpgrades || string.IsNullOrWhiteSpace(packageInfo.Arguments)) return config;
1729+
1730+
var packageArgumentsUnencrypted = packageInfo.Arguments.ContainsSafe(" --") && packageInfo.Arguments.ToStringSafe().Length > 4 ? packageInfo.Arguments : NugetEncryptionUtility.DecryptString(packageInfo.Arguments);
1731+
1732+
var sensitiveArgs = true;
1733+
if (!ArgumentsUtility.SensitiveArgumentsProvided(packageArgumentsUnencrypted))
1734+
{
1735+
sensitiveArgs = false;
1736+
this.Log().Debug(ChocolateyLoggers.Verbose, "{0} - Adding remembered arguments: {1}".FormatWith(packageInfo.Package.Id, packageArgumentsUnencrypted.EscapeCurlyBraces()));
1737+
}
1738+
1739+
var packageArgumentsSplit = packageArgumentsUnencrypted.Split(new[] { " --" }, StringSplitOptions.RemoveEmptyEntries);
1740+
var packageArguments = new List<string>();
1741+
foreach (var packageArgument in packageArgumentsSplit.OrEmpty())
1742+
{
1743+
var packageArgumentSplit = packageArgument.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
1744+
var optionName = packageArgumentSplit[0].ToStringSafe();
1745+
var optionValue = string.Empty;
1746+
if (packageArgumentSplit.Length == 2)
1747+
{
1748+
optionValue = packageArgumentSplit[1].ToStringSafe().UnquoteSafe();
1749+
if (optionValue.StartsWith("'")) optionValue.UnquoteSafe();
1750+
}
1751+
1752+
if (sensitiveArgs)
1753+
{
1754+
this.Log().Debug(ChocolateyLoggers.Verbose, "{0} - Adding '{1}' to arguments. Values not shown due to detected sensitive arguments".FormatWith(packageInfo.Package.Id, optionName.EscapeCurlyBraces()));
1755+
}
1756+
packageArguments.Add("--{0}{1}".FormatWith(optionName, string.IsNullOrWhiteSpace(optionValue) ? string.Empty : "=" + optionValue));
1757+
}
1758+
1759+
var originalConfig = config.DeepCopy();
1760+
var rememberedOptionSet = new OptionSet();
1761+
1762+
rememberedOptionSet
1763+
.Add("pre|prerelease",
1764+
"Prerelease - Include Prereleases? Defaults to false.",
1765+
option => config.Prerelease = option != null)
1766+
.Add("i|ignoredependencies|ignore-dependencies",
1767+
"IgnoreDependencies - Ignore dependencies when installing package(s). Defaults to false.",
1768+
option => config.IgnoreDependencies = option != null)
1769+
.Add("x86|forcex86",
1770+
"ForceX86 - Force x86 (32bit) installation on 64 bit systems. Defaults to false.",
1771+
option => config.ForceX86 = option != null)
1772+
.Add("ia=|installargs=|install-args=|installarguments=|install-arguments=",
1773+
"InstallArguments - Install Arguments to pass to the native installer in the package. Defaults to unspecified.",
1774+
option => config.InstallArguments = option.remove_surrounding_quotes())
1775+
.Add("o|override|overrideargs|overridearguments|override-arguments",
1776+
"OverrideArguments - Should install arguments be used exclusively without appending to current package passed arguments? Defaults to false.",
1777+
option => config.OverrideArguments = option != null)
1778+
.Add("argsglobal|args-global|installargsglobal|install-args-global|applyargstodependencies|apply-args-to-dependencies|apply-install-arguments-to-dependencies",
1779+
"Apply Install Arguments To Dependencies - Should install arguments be applied to dependent packages? Defaults to false.",
1780+
option => config.ApplyInstallArgumentsToDependencies = option != null)
1781+
.Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=",
1782+
"PackageParameters - Parameters to pass to the package. Defaults to unspecified.",
1783+
option => config.PackageParameters = option.remove_surrounding_quotes())
1784+
.Add("paramsglobal|params-global|packageparametersglobal|package-parameters-global|applyparamstodependencies|apply-params-to-dependencies|apply-package-parameters-to-dependencies",
1785+
"Apply Package Parameters To Dependencies - Should package parameters be applied to dependent packages? Defaults to false.",
1786+
option => config.ApplyPackageParametersToDependencies = option != null)
1787+
.Add("allowdowngrade|allow-downgrade",
1788+
"AllowDowngrade - Should an attempt at downgrading be allowed? Defaults to false.",
1789+
option => config.AllowDowngrade = option != null)
1790+
.Add("u=|user=",
1791+
"User - used with authenticated feeds. Defaults to empty.",
1792+
option => config.SourceCommand.Username = option.remove_surrounding_quotes())
1793+
.Add("p=|password=",
1794+
"Password - the user's password to the source. Defaults to empty.",
1795+
option => config.SourceCommand.Password = option.remove_surrounding_quotes())
1796+
.Add("cert=",
1797+
"Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.",
1798+
option => config.SourceCommand.Certificate = option.remove_surrounding_quotes())
1799+
.Add("cp=|certpassword=",
1800+
"Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.",
1801+
option => config.SourceCommand.CertificatePassword = option.remove_surrounding_quotes())
1802+
.Add("timeout=|execution-timeout=",
1803+
"CommandExecutionTimeout (in seconds) - The time to allow a command to finish before timing out. Overrides the default execution timeout in the configuration of {0} seconds. '0' for infinite starting in 0.10.4.".format_with(config.CommandExecutionTimeoutSeconds.to_string()),
1804+
option =>
1805+
{
1806+
int timeout = 0;
1807+
var timeoutString = option.remove_surrounding_quotes();
1808+
int.TryParse(timeoutString, out timeout);
1809+
if (timeout > 0 || timeoutString.is_equal_to("0"))
1810+
{
1811+
config.CommandExecutionTimeoutSeconds = timeout;
1812+
}
1813+
})
1814+
.Add("c=|cache=|cachelocation=|cache-location=",
1815+
"CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.",
1816+
option => config.CacheLocation = option.remove_surrounding_quotes())
1817+
.Add("use-system-powershell",
1818+
"UseSystemPowerShell - Execute PowerShell using an external process instead of the built-in PowerShell host. Should only be used when internal host is failing. Available in 0.9.10+.",
1819+
option => config.Features.UsePowerShellHost = option != null);
1820+
1821+
rememberedOptionSet.Parse(packageArguments);
1822+
1823+
// there may be overrides from the user running upgrade
1824+
if (!string.IsNullOrWhiteSpace(originalConfig.PackageParameters)) config.PackageParameters = originalConfig.PackageParameters;
1825+
if (!string.IsNullOrWhiteSpace(originalConfig.InstallArguments)) config.InstallArguments = originalConfig.InstallArguments;
1826+
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.Username)) config.SourceCommand.Username = originalConfig.SourceCommand.Username;
1827+
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.Password)) config.SourceCommand.Password = originalConfig.SourceCommand.Password;
1828+
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.Certificate)) config.SourceCommand.Certificate = originalConfig.SourceCommand.Certificate;
1829+
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.CertificatePassword)) config.SourceCommand.CertificatePassword = originalConfig.SourceCommand.CertificatePassword;
1830+
1831+
if (originalConfig.CacheLocationArgumentWasPassed && !string.IsNullOrWhiteSpace(originalConfig.CacheLocation))
1832+
{
1833+
config.CacheLocation = originalConfig.CacheLocation;
1834+
}
1835+
1836+
if (originalConfig.CommandExecutionTimeoutSecondsArgumentWasPassed)
1837+
{
1838+
config.CommandExecutionTimeoutSeconds = originalConfig.CommandExecutionTimeoutSeconds;
1839+
}
1840+
1841+
// We can't override switches because we don't know here if they were set on the command line
1842+
1843+
return config;
1844+
}
1845+
17251846
private bool HasMissingDependency(PackageResult package, List<PackageResult> allLocalPackages)
17261847
{
17271848
foreach (var dependency in package.PackageMetadata.DependencyGroups.SelectMany(d => d.Packages))

0 commit comments

Comments
 (0)