forked from chocolatey/choco
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChocolateyExportCommand.cs
288 lines (240 loc) · 15 KB
/
ChocolateyExportCommand.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Copyright © 2017 - 2021 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace chocolatey.infrastructure.app.commands
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using attributes;
using commandline;
using configuration;
using filesystem;
using infrastructure.commands;
using logging;
using services;
using tolerance;
[CommandFor("export", "exports list of currently installed packages")]
public class ChocolateyExportCommand : ICommand
{
private readonly INugetService _nugetService;
private readonly IFileSystem _fileSystem;
private readonly IChocolateyPackageInformationService _packageInfoService;
private readonly IChocolateyPackageService _packageService;
public ChocolateyExportCommand(
INugetService nugetService,
IFileSystem fileSystem,
IChocolateyPackageInformationService packageInfoService,
IChocolateyPackageService packageService)
{
_nugetService = nugetService;
_fileSystem = fileSystem;
_packageInfoService = packageInfoService;
_packageService = packageService;
}
public void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
{
optionSet
.Add("o=|output-file-path=",
"Output File Path - the path to where the list of currently installed packages should be saved. Defaults to packages.config.",
option => configuration.ExportCommand.OutputFilePath = option.remove_surrounding_quotes())
.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 1.2.0+",
option => configuration.ExportCommand.IncludeRememberedPackageArguments = option != null)
.Add("exclude-pins",
"Exclude Pins - controls whether or not pins are included. Only applies if remembered arguments are exported. Defaults to false.",
option => configuration.ExportCommand.ExcludePins = option != null)
;
}
public void handle_additional_argument_parsing(IList<string> unparsedArguments, ChocolateyConfiguration configuration)
{
configuration.Input = string.Join(" ", unparsedArguments);
if (string.IsNullOrWhiteSpace(configuration.ExportCommand.OutputFilePath) && unparsedArguments.Count >=1)
{
configuration.ExportCommand.OutputFilePath = unparsedArguments[0];
}
// If no value has been provided for the OutputFilePath, default to packages.config
if (string.IsNullOrWhiteSpace(configuration.ExportCommand.OutputFilePath))
{
configuration.ExportCommand.OutputFilePath = "packages.config";
}
}
public void handle_validation(ChocolateyConfiguration configuration)
{
// Currently, no additional validation is required.
}
public void help_message(ChocolateyConfiguration configuration)
{
this.Log().Info(ChocolateyLoggers.Important, "Export Command");
this.Log().Info(@"
Export all currently installed packages to a file.
This is especially helpful when re-building a machine that was created
using Chocolatey. Export all packages to a file, and then re-install
those packages onto new machine using `choco install packages.config`.
NOTE: Available with 0.11.0+.
");
"chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage");
"chocolatey".Log().Info(@"
choco export [<options/switches>]
");
"chocolatey".Log().Info(ChocolateyLoggers.Important, "Examples");
"chocolatey".Log().Info(@"
choco export
choco export --include-version-numbers
choco export --include-version-numbers --include-remembered-arguments
choco export --include-remembered-arguments --exclude-pins
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.
");
"chocolatey".Log().Info(ChocolateyLoggers.Important, "Exit Codes");
"chocolatey".Log().Info(@"
Exit codes that normally result from running this command.
Normal:
- 0: operation was successful, no issues detected
- -1 or 1: an error has occurred
If you find other exit codes that we have not yet documented, please
file a ticket so we can document it at
https://github.com/chocolatey/choco/issues/new/choose.
");
"chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches");
}
public bool may_require_admin_access()
{
return false;
}
public void noop(ChocolateyConfiguration configuration)
{
this.Log().Info("Export would have been with options: {0} Output File Path={1}{0} Include Version Numbers:{2}{0} Include Remembered Arguments: {3}{0} Exclude Pins: {4}".format_with(
Environment.NewLine, configuration.ExportCommand.OutputFilePath,
configuration.ExportCommand.IncludeVersionNumbers,
configuration.ExportCommand.IncludeRememberedPackageArguments,
configuration.ExportCommand.ExcludePins));
}
public void run(ChocolateyConfiguration configuration)
{
var installedPackages = _nugetService.get_all_installed_packages(configuration);
var xmlWriterSettings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding(false) };
// Add the options set from the install command.
ConfigurationOptions.OptionSet.Remove("o");
var installCommand = new ChocolateyInstallCommand(_packageService);
// If the --source option is available, assume that the install command arguments have already been added.
// This is required for when this method multiple times in a row, such as in the unit tests.
if (!ConfigurationOptions.OptionSet.Contains("source"))
{
installCommand.configure_argument_parser(ConfigurationOptions.OptionSet, configuration);
}
// Make sure we have a clean configuration to revert to after parsing remembered arguments.
configuration.start_backup();
FaultTolerance.try_catch_with_logging_exception(
() =>
{
var packagesConfig = new PackagesConfigFileSettings();
packagesConfig.Packages = new HashSet<PackagesConfigFilePackageSetting>();
using (var stringWriter = new StringWriter())
{
using (var xw = XmlWriter.Create(stringWriter, xmlWriterSettings))
{
foreach (var packageResult in installedPackages)
{
var packageElement = new PackagesConfigFilePackageSetting
{
Id = packageResult.PackageMetadata.Id
};
if (configuration.ExportCommand.IncludeVersionNumbers)
{
packageElement.Version = packageResult.PackageMetadata.Version.ToString();
}
if (configuration.ExportCommand.IncludeRememberedPackageArguments)
{
var pkgInfo = _packageInfoService.get_package_information(packageResult.PackageMetadata);
configuration.Features.UseRememberedArgumentsForUpgrades = true;
_nugetService.set_package_config_for_upgrade(configuration, pkgInfo);
// Mirrors the arguments captured in ChocolateyPackageService.capture_arguments()
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 (configuration.AllowMultipleVersions) packageElement.AllowMultipleVersions = 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;
if (!configuration.ExportCommand.ExcludePins && pkgInfo.IsPinned)
{
xw.WriteAttributeString("pinPackage", "true");
}
// Make sure to reset the configuration so as to be able to parse the next set of remembered arguments
configuration.reset_config();
}
packagesConfig.Packages.Add(packageElement);
}
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
var packagesConfigSerializer = new XmlSerializer(typeof(PackagesConfigFileSettings));
packagesConfigSerializer.Serialize(xw, packagesConfig, ns);
}
var fullOutputFilePath = _fileSystem.get_full_path(configuration.ExportCommand.OutputFilePath);
var fileExists = _fileSystem.file_exists(fullOutputFilePath);
// If the file doesn't already exist, just write the new one out directly
if (!fileExists)
{
_fileSystem.write_file(
fullOutputFilePath,
stringWriter.GetStringBuilder().ToString(),
new UTF8Encoding(false));
return;
}
// Otherwise, create an update file, and resiliently move it into place.
var tempUpdateFile = fullOutputFilePath + "." + Process.GetCurrentProcess().Id + ".update";
_fileSystem.write_file(tempUpdateFile,
stringWriter.GetStringBuilder().ToString(),
new UTF8Encoding(false));
_fileSystem.replace_file(tempUpdateFile, fullOutputFilePath, fullOutputFilePath + ".backup");
}
},
errorMessage: "Error exporting currently installed packages",
throwError: true
);
}
}
}