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

(#2503) Add ability to export saved arguments #2506

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ $commandOptions = @{
config = "--name='' --value=''"
feature = "--name=''"
apikey = "--source='' --api-key='' --remove"
export = "--include-version-numbers --output-file-path=''"
export = "--include-version-numbers --output-file-path='' --include-remembered-arguments"
template = "--name=''"
cache = "--expired"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,20 @@ public abstract class ChocolateyExportCommandSpecsBase : TinySpec
protected Mock<INugetService> NugetService = new Mock<INugetService>();
protected Mock<IFileSystem> FileSystem = new Mock<IFileSystem>();
protected ChocolateyConfiguration Configuration = new ChocolateyConfiguration();
protected Mock<IChocolateyPackageInformationService> PackageInfoService = new Mock<IChocolateyPackageInformationService>();
protected Mock<IChocolateyPackageService> PackageService = new Mock<IChocolateyPackageService>();

public override void Context()
{
Command = new ChocolateyExportCommand(NugetService.Object, FileSystem.Object);
Command = new ChocolateyExportCommand(NugetService.Object, FileSystem.Object, PackageInfoService.Object, PackageService.Object);
}

public void Reset()
{
NugetService.ResetCalls();
FileSystem.ResetCalls();
PackageInfoService.ResetCalls();
PackageService.ResetCalls();
}
}

Expand Down Expand Up @@ -104,6 +108,18 @@ public void Should_add_include_version_to_the_option_set()
{
_optionSet.Contains("include-version").Should().BeTrue();
}

[Fact]
public void Should_add_include_arguments_to_the_option_set()
{
_optionSet.Contains("include-arguments").Should().BeTrue();
}

[Fact]
public void Should_add_include_remembered_arguments_to_the_option_set()
{
_optionSet.Contains("include-remembered-arguments").Should().BeTrue();
}
}

public class When_handling_additional_argument_parsing : ChocolateyExportCommandSpecsBase
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -419,11 +419,16 @@ private static void SetGlobalOptions(IList<string> args, ChocolateyConfiguration
if (timeout > 0 || timeoutString.IsEqualTo("0"))
{
config.CommandExecutionTimeoutSeconds = timeout;
config.CommandExecutionTimeoutSecondsArgumentWasPassed = true;
}
})
.Add("c=|cache=|cachelocation=|cache-location=",
"CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.",
option => config.CacheLocation = option.UnquoteSafe())
option =>
{
config.CacheLocation = option.UnquoteSafe();
config.CacheLocationArgumentWasPassed = true;
})
.Add("allowunofficial|allow-unofficial|allowunofficialbuild|allow-unofficial-build",
"AllowUnofficialBuild - When not using the official build you must set this flag for choco to continue.",
option => config.AllowUnofficialBuild = option != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using chocolatey.infrastructure.app.attributes;
using chocolatey.infrastructure.commandline;
using chocolatey.infrastructure.app.configuration;
Expand All @@ -36,11 +37,19 @@ public class ChocolateyExportCommand : ICommand
{
private readonly INugetService _nugetService;
private readonly IFileSystem _fileSystem;

public ChocolateyExportCommand(INugetService nugetService, IFileSystem fileSystem)
private readonly IChocolateyPackageInformationService _packageInfoService;
private readonly IChocolateyPackageService _packageService;
TheCakeIsNaOH marked this conversation as resolved.
Show resolved Hide resolved

public ChocolateyExportCommand(
INugetService nugetService,
IFileSystem fileSystem,
IChocolateyPackageInformationService packageInfoService,
IChocolateyPackageService packageService)
{
_nugetService = nugetService;
_fileSystem = fileSystem;
_packageInfoService = packageInfoService;
_packageService = packageService;
}

public void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration)
Expand All @@ -52,6 +61,9 @@ public void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration
.Add("include-version-numbers|include-version",
"Include Version Numbers - controls whether or not version numbers for each package appear in generated file. Defaults to false.",
option => configuration.ExportCommand.IncludeVersionNumbers = option != null)
.Add("include-arguments|include-remembered-arguments",
"Include Remembered Arguments - controls whether or not remembered arguments for each package appear in generated file. Defaults to false. Available in 2.3.0+",
option => configuration.ExportCommand.IncludeRememberedPackageArguments = option != null)
;
}

Expand Down Expand Up @@ -95,12 +107,14 @@ choco export [<options/switches>]
"chocolatey".Log().Info(@"
choco export
choco export --include-version-numbers
choco export --include-version-numbers --include-remembered-arguments
choco export ""'c:\temp\packages.config'""
choco export ""'c:\temp\packages.config'"" --include-version-numbers
choco export -o=""'c:\temp\packages.config'""
choco export -o=""'c:\temp\packages.config'"" --include-version-numbers
choco export --output-file-path=""'c:\temp\packages.config'""
choco export --output-file-path=""'c:\temp\packages.config'"" --include-version-numbers
choco export --output-file-path=""""'c:\temp\packages.config'"""" --include-remembered-arguments

NOTE: See scripting in the command reference (`choco -?`) for how to
write proper scripts and integrations.
Expand Down Expand Up @@ -131,39 +145,80 @@ public bool MayRequireAdminAccess()

public void DryRun(ChocolateyConfiguration configuration)
{
this.Log().Info("Export would have been with options: {0} Output File Path={1}{0} Include Version Numbers:{2}".FormatWith(Environment.NewLine, configuration.ExportCommand.OutputFilePath, configuration.ExportCommand.IncludeVersionNumbers));
this.Log().Info("Export would have been with options: {0} Output File Path={1}{0} Include Version Numbers:{2}{0} Include Remembered Arguments: {3}".FormatWith(Environment.NewLine, configuration.ExportCommand.OutputFilePath, configuration.ExportCommand.IncludeVersionNumbers, configuration.ExportCommand.IncludeRememberedPackageArguments));
}

public void Run(ChocolateyConfiguration configuration)
{
var packageResults = _nugetService.GetInstalledPackages(configuration);
var settings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding(false) };
var installedPackages = _nugetService.GetInstalledPackages(configuration);
var xmlWriterSettings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding(false) };

configuration.CreateBackup();

FaultTolerance.TryCatchWithLoggingException(
() =>
{
var packagesConfig = new PackagesConfigFileSettings();
packagesConfig.Packages = new HashSet<PackagesConfigFilePackageSetting>();

using (var stringWriter = new StringWriter())
{
using (var xw = XmlWriter.Create(stringWriter, settings))
using (var xw = XmlWriter.Create(stringWriter, xmlWriterSettings))
{
xw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
xw.WriteStartElement("packages");

foreach (var packageResult in packageResults)
foreach (var packageResult in installedPackages)
{
xw.WriteStartElement("package");
xw.WriteAttributeString("id", packageResult.PackageMetadata.Id);
var packageElement = new PackagesConfigFilePackageSetting
{
Id = packageResult.PackageMetadata.Id
};

if (configuration.ExportCommand.IncludeVersionNumbers)
{
xw.WriteAttributeString("version", packageResult.PackageMetadata.Version.ToString());
packageElement.Version = packageResult.PackageMetadata.Version.ToString();
}

xw.WriteEndElement();
if (configuration.ExportCommand.IncludeRememberedPackageArguments)
{
var pkgInfo = _packageInfoService.Get(packageResult.PackageMetadata);
configuration.Features.UseRememberedArgumentsForUpgrades = true;
var rememberedConfig = _nugetService.GetPackageConfigFromRememberedArguments(configuration, pkgInfo);

// Mirrors the arguments captured in ChocolateyPackageService.CaptureArguments()
if (configuration.Prerelease) packageElement.Prerelease = true;
if (configuration.IgnoreDependencies) packageElement.IgnoreDependencies = true;
if (configuration.ForceX86) packageElement.ForceX86 = true;
if (!string.IsNullOrWhiteSpace(configuration.InstallArguments)) packageElement.InstallArguments = configuration.InstallArguments;
if (configuration.OverrideArguments) packageElement.OverrideArguments = true;
if (configuration.ApplyInstallArgumentsToDependencies) packageElement.ApplyInstallArgumentsToDependencies = true;
if (!string.IsNullOrWhiteSpace(configuration.PackageParameters)) packageElement.PackageParameters = configuration.PackageParameters;
if (configuration.ApplyPackageParametersToDependencies) packageElement.ApplyPackageParametersToDependencies = true;
if (configuration.AllowDowngrade) packageElement.AllowDowngrade = true;
if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.Username)) packageElement.User = configuration.SourceCommand.Username;
if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.Password)) packageElement.Password = configuration.SourceCommand.Password;
if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.Certificate)) packageElement.Cert = configuration.SourceCommand.Certificate;
if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.CertificatePassword)) packageElement.CertPassword = configuration.SourceCommand.CertificatePassword;
// Arguments from the global options set
if (configuration.CommandExecutionTimeoutSeconds != ApplicationParameters.DefaultWaitForExitInSeconds)
{
packageElement.ExecutionTimeout = configuration.CommandExecutionTimeoutSeconds;
}
// This was discussed in the PR, and because it is potentially system specific, it should not be included in the exported file
// if (!string.IsNullOrWhiteSpace(configuration.CacheLocation)) packageElement.CacheLocation = configuration.CacheLocation;
// if (configuration.Features.FailOnStandardError) packageElement.FailOnStderr = true;
// if (!configuration.Features.UsePowerShellHost) packageElement.UseSystemPowershell = true;

// Make sure to reset the configuration so as to be able to parse the next set of remembered arguments
configuration.RevertChanges();
}

packagesConfig.Packages.Add(packageElement);
}

xw.WriteEndElement();
xw.Flush();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");

var packagesConfigSerializer = new XmlSerializer(typeof(PackagesConfigFileSettings));
packagesConfigSerializer.Serialize(xw, packagesConfig, ns);
}

var fullOutputFilePath = _fileSystem.GetFullPath(configuration.ExportCommand.OutputFilePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,10 @@ private void AppendOutput(StringBuilder propertyValues, string append)

// configuration set variables
public string CacheLocation { get; set; }
public bool CacheLocationArgumentWasPassed { get; set; }

public int CommandExecutionTimeoutSeconds { get; set; }
public bool CommandExecutionTimeoutSecondsArgumentWasPassed { get; set; }
public int WebRequestTimeoutSeconds { get; set; }
public string DefaultTemplateName { get; set; }

Expand Down Expand Up @@ -718,6 +720,7 @@ public sealed class ProxyConfiguration
public sealed class ExportCommandConfiguration
{
public bool IncludeVersionNumbers { get; set; }
public bool IncludeRememberedPackageArguments { get; set; }
TheCakeIsNaOH marked this conversation as resolved.
Show resolved Hide resolved

public string OutputFilePath { get; set; }
}
Expand Down
Loading
Loading