Skip to content

Commit 0907c07

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 dc243a8 commit 0907c07

File tree

2 files changed

+175
-14
lines changed

2 files changed

+175
-14
lines changed

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

+11
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
using System.Collections.Concurrent;
1919
using System.Collections.Generic;
2020
using chocolatey.infrastructure.app.configuration;
21+
using chocolatey.infrastructure.app.domain;
2122
using chocolatey.infrastructure.results;
2223

2324
namespace chocolatey.infrastructure.app.services
@@ -67,6 +68,16 @@ public interface INugetService : ISourceRunner
6768
/// <param name="config">The configuration</param>
6869
IEnumerable<PackageResult> GetInstalledPackages(ChocolateyConfiguration config);
6970

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

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

+164-14
Original file line numberDiff line numberDiff line change
@@ -1216,7 +1216,7 @@ public virtual ConcurrentDictionary<string, PackageResult> Upgrade(ChocolateyCon
12161216
continue;
12171217
}
12181218

1219-
SetConfigFromRememberedArguments(config, pkgInfo);
1219+
config = GetPackageConfigFromRememberedArguments(config, pkgInfo);
12201220
var pathResolver = NugetCommon.GetPathResolver(_fileSystem);
12211221
var nugetProject = new FolderNuGetProject(ApplicationParameters.PackagesLocation, pathResolver, NuGetFramework.AnyFramework);
12221222

@@ -1354,12 +1354,12 @@ public virtual ConcurrentDictionary<string, PackageResult> Upgrade(ChocolateyCon
13541354
var logMessage = "{0} is pinned. Skipping pinned package.".FormatWith(packageName);
13551355
packageResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage));
13561356
packageResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage));
1357-
1357+
13581358
if (config.RegularOutput)
13591359
{
13601360
this.Log().Warn(ChocolateyLoggers.Important, logMessage);
13611361
}
1362-
1362+
13631363
continue;
13641364
}
13651365
else
@@ -1371,7 +1371,7 @@ public virtual ConcurrentDictionary<string, PackageResult> Upgrade(ChocolateyCon
13711371
{
13721372
this.Log().Warn(ChocolateyLoggers.Important, logMessage);
13731373
}
1374-
1374+
13751375
config.PinPackage = true;
13761376
}
13771377
}
@@ -1453,7 +1453,7 @@ public virtual ConcurrentDictionary<string, PackageResult> Upgrade(ChocolateyCon
14531453
}
14541454

14551455
var removedSources = new HashSet<SourcePackageDependencyInfo>();
1456-
1456+
14571457
if (!config.UpgradeCommand.IgnorePinned)
14581458
{
14591459
removedSources.AddRange(RemovePinnedSourceDependencies(sourcePackageDependencyInfos, allLocalPackages));
@@ -1937,12 +1937,7 @@ public virtual ConcurrentDictionary<string, PackageResult> GetOutdated(Chocolate
19371937
return outdatedPackages;
19381938
}
19391939

1940-
/// <summary>
1941-
/// Sets the configuration for the package upgrade
1942-
/// </summary>
1943-
/// <param name="config">The configuration.</param>
1944-
/// <param name="packageInfo">The package information.</param>
1945-
/// <returns>The original unmodified configuration, so it can be reset after upgrade</returns>
1940+
[Obsolete("This method is deprecated and will be removed in v3.")]
19461941
protected virtual ChocolateyConfiguration SetConfigFromRememberedArguments(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo)
19471942
{
19481943
if (!config.Features.UseRememberedArgumentsForUpgrades || string.IsNullOrWhiteSpace(packageInfo.Arguments))
@@ -1968,16 +1963,16 @@ protected virtual ChocolateyConfiguration SetConfigFromRememberedArguments(Choco
19681963
ConfigurationOptions.OptionSet.Parse(packageArguments);
19691964

19701965
// there may be overrides from the user running upgrade
1971-
if (!string.IsNullOrWhiteSpace(originalConfig.PackageParameters))
1966+
if (!string.IsNullOrWhiteSpace(originalConfig.PackageParameters))
19721967
{
19731968
config.PackageParameters = originalConfig.PackageParameters;
19741969
}
1975-
1970+
19761971
if (!string.IsNullOrWhiteSpace(originalConfig.InstallArguments))
19771972
{
19781973
config.InstallArguments = originalConfig.InstallArguments;
19791974
}
1980-
1975+
19811976
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.Username))
19821977
{
19831978
config.SourceCommand.Username = originalConfig.SourceCommand.Username;
@@ -2011,6 +2006,161 @@ protected virtual ChocolateyConfiguration SetConfigFromRememberedArguments(Choco
20112006
return originalConfig;
20122007
}
20132008

2009+
/// <summary>
2010+
/// Gets the configuration from remembered arguments
2011+
/// </summary>
2012+
/// <param name="config">The original configuration.</param>
2013+
/// <param name="packageInfo">The package information.</param>
2014+
/// <returns>The modified configuration, so it can be used</returns>
2015+
public virtual ChocolateyConfiguration GetPackageConfigFromRememberedArguments(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo)
2016+
{
2017+
if (!config.Features.UseRememberedArgumentsForUpgrades || string.IsNullOrWhiteSpace(packageInfo.Arguments))
2018+
{
2019+
return config;
2020+
}
2021+
2022+
var packageArgumentsUnencrypted = packageInfo.Arguments.ContainsSafe(" --") && packageInfo.Arguments.ToStringSafe().Length > 4 ? packageInfo.Arguments : NugetEncryptionUtility.DecryptString(packageInfo.Arguments);
2023+
2024+
var sensitiveArgs = true;
2025+
if (!ArgumentsUtility.SensitiveArgumentsProvided(packageArgumentsUnencrypted))
2026+
{
2027+
sensitiveArgs = false;
2028+
this.Log().Debug(ChocolateyLoggers.Verbose, "{0} - Adding remembered arguments: {1}".FormatWith(packageInfo.Package.Id, packageArgumentsUnencrypted.EscapeCurlyBraces()));
2029+
}
2030+
2031+
var packageArgumentsSplit = packageArgumentsUnencrypted.Split(new[] { " --" }, StringSplitOptions.RemoveEmptyEntries);
2032+
var packageArguments = new List<string>();
2033+
foreach (var packageArgument in packageArgumentsSplit.OrEmpty())
2034+
{
2035+
var packageArgumentSplit = packageArgument.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
2036+
var optionName = packageArgumentSplit[0].ToStringSafe();
2037+
var optionValue = string.Empty;
2038+
if (packageArgumentSplit.Length == 2)
2039+
{
2040+
optionValue = packageArgumentSplit[1].ToStringSafe().UnquoteSafe();
2041+
if (optionValue.StartsWith("'"))
2042+
{
2043+
optionValue.UnquoteSafe();
2044+
}
2045+
}
2046+
2047+
if (sensitiveArgs)
2048+
{
2049+
this.Log().Debug(ChocolateyLoggers.Verbose, "{0} - Adding '{1}' to arguments. Values not shown due to detected sensitive arguments".FormatWith(packageInfo.Package.Id, optionName.EscapeCurlyBraces()));
2050+
}
2051+
packageArguments.Add("--{0}{1}".FormatWith(optionName, string.IsNullOrWhiteSpace(optionValue) ? string.Empty : "=" + optionValue));
2052+
}
2053+
2054+
var originalConfig = config.DeepCopy();
2055+
var rememberedOptionSet = new OptionSet();
2056+
2057+
rememberedOptionSet
2058+
.Add("pre|prerelease",
2059+
"Prerelease - Include Prereleases? Defaults to false.",
2060+
option => config.Prerelease = option != null)
2061+
.Add("i|ignoredependencies|ignore-dependencies",
2062+
"IgnoreDependencies - Ignore dependencies when installing package(s). Defaults to false.",
2063+
option => config.IgnoreDependencies = option != null)
2064+
.Add("x86|forcex86",
2065+
"ForceX86 - Force x86 (32bit) installation on 64 bit systems. Defaults to false.",
2066+
option => config.ForceX86 = option != null)
2067+
.Add("ia=|installargs=|install-args=|installarguments=|install-arguments=",
2068+
"InstallArguments - Install Arguments to pass to the native installer in the package. Defaults to unspecified.",
2069+
option => config.InstallArguments = option.UnquoteSafe())
2070+
.Add("o|override|overrideargs|overridearguments|override-arguments",
2071+
"OverrideArguments - Should install arguments be used exclusively without appending to current package passed arguments? Defaults to false.",
2072+
option => config.OverrideArguments = option != null)
2073+
.Add("argsglobal|args-global|installargsglobal|install-args-global|applyargstodependencies|apply-args-to-dependencies|apply-install-arguments-to-dependencies",
2074+
"Apply Install Arguments To Dependencies - Should install arguments be applied to dependent packages? Defaults to false.",
2075+
option => config.ApplyInstallArgumentsToDependencies = option != null)
2076+
.Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=",
2077+
"PackageParameters - Parameters to pass to the package. Defaults to unspecified.",
2078+
option => config.PackageParameters = option.UnquoteSafe())
2079+
.Add("paramsglobal|params-global|packageparametersglobal|package-parameters-global|applyparamstodependencies|apply-params-to-dependencies|apply-package-parameters-to-dependencies",
2080+
"Apply Package Parameters To Dependencies - Should package parameters be applied to dependent packages? Defaults to false.",
2081+
option => config.ApplyPackageParametersToDependencies = option != null)
2082+
.Add("allowdowngrade|allow-downgrade",
2083+
"AllowDowngrade - Should an attempt at downgrading be allowed? Defaults to false.",
2084+
option => config.AllowDowngrade = option != null)
2085+
.Add("u=|user=",
2086+
"User - used with authenticated feeds. Defaults to empty.",
2087+
option => config.SourceCommand.Username = option.UnquoteSafe())
2088+
.Add("p=|password=",
2089+
"Password - the user's password to the source. Defaults to empty.",
2090+
option => config.SourceCommand.Password = option.UnquoteSafe())
2091+
.Add("cert=",
2092+
"Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.",
2093+
option => config.SourceCommand.Certificate = option.UnquoteSafe())
2094+
.Add("cp=|certpassword=",
2095+
"Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.",
2096+
option => config.SourceCommand.CertificatePassword = option.UnquoteSafe())
2097+
.Add("timeout=|execution-timeout=",
2098+
"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.".FormatWith(config.CommandExecutionTimeoutSeconds.ToString()),
2099+
option =>
2100+
{
2101+
var timeout = 0;
2102+
var timeoutString = option.UnquoteSafe();
2103+
int.TryParse(timeoutString, out timeout);
2104+
if (timeout > 0 || timeoutString.IsEqualTo("0"))
2105+
{
2106+
config.CommandExecutionTimeoutSeconds = timeout;
2107+
}
2108+
})
2109+
.Add("c=|cache=|cachelocation=|cache-location=",
2110+
"CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.",
2111+
option => config.CacheLocation = option.UnquoteSafe())
2112+
.Add("use-system-powershell",
2113+
"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+.",
2114+
option => config.Features.UsePowerShellHost = option != null);
2115+
2116+
rememberedOptionSet.Parse(packageArguments);
2117+
2118+
// there may be overrides from the user running upgrade
2119+
if (!string.IsNullOrWhiteSpace(originalConfig.PackageParameters))
2120+
{
2121+
config.PackageParameters = originalConfig.PackageParameters;
2122+
}
2123+
2124+
if (!string.IsNullOrWhiteSpace(originalConfig.InstallArguments))
2125+
{
2126+
config.InstallArguments = originalConfig.InstallArguments;
2127+
}
2128+
2129+
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.Username))
2130+
{
2131+
config.SourceCommand.Username = originalConfig.SourceCommand.Username;
2132+
}
2133+
2134+
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.Password))
2135+
{
2136+
config.SourceCommand.Password = originalConfig.SourceCommand.Password;
2137+
}
2138+
2139+
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.Certificate))
2140+
{
2141+
config.SourceCommand.Certificate = originalConfig.SourceCommand.Certificate;
2142+
}
2143+
2144+
if (!string.IsNullOrWhiteSpace(originalConfig.SourceCommand.CertificatePassword))
2145+
{
2146+
config.SourceCommand.CertificatePassword = originalConfig.SourceCommand.CertificatePassword;
2147+
}
2148+
2149+
if (originalConfig.CacheLocationArgumentWasPassed && !string.IsNullOrWhiteSpace(originalConfig.CacheLocation))
2150+
{
2151+
config.CacheLocation = originalConfig.CacheLocation;
2152+
}
2153+
2154+
if (originalConfig.CommandExecutionTimeoutSecondsArgumentWasPassed)
2155+
{
2156+
config.CommandExecutionTimeoutSeconds = originalConfig.CommandExecutionTimeoutSeconds;
2157+
}
2158+
2159+
// We can't override switches because we don't know here if they were set on the command line
2160+
2161+
return config;
2162+
}
2163+
20142164
private bool HasMissingDependency(PackageResult package, List<PackageResult> allLocalPackages)
20152165
{
20162166
foreach (var dependency in package.PackageMetadata.DependencyGroups.SelectMany(d => d.Packages))

0 commit comments

Comments
 (0)