-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathSavePSResource.cs
More file actions
327 lines (281 loc) · 12.9 KB
/
SavePSResource.cs
File metadata and controls
327 lines (281 loc) · 12.9 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.PowerShell.PSResourceGet.UtilClasses;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Net;
using Dbg = System.Diagnostics.Debug;
namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
{
/// <summary>
/// The Save-PSResource cmdlet saves a resource to a machine.
/// It returns nothing.
/// </summary>
[Cmdlet(VerbsData.Save, "PSResource", DefaultParameterSetName = "IncludeXmlParameterSet", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low)]
[Alias("svres")]
public sealed class SavePSResource : PSCmdlet
{
#region Members
private const string InputObjectParameterSet = "InputObjectParameterSet";
private const string AsNupkgParameterSet = "AsNupkgParameterSet";
private const string IncludeXmlParameterSet = "IncludeXmlParameterSet";
InstallHelper _installHelper;
#endregion
#region Parameters
/// <summary>
/// Specifies the exact names of resources to save from a repository.
/// A comma-separated list of module names is accepted. The resource name must match the resource name in the repository.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = AsNupkgParameterSet, HelpMessage = "Name of the package(s) to save.")]
[Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = IncludeXmlParameterSet, HelpMessage = "Name of the package(s) to save.")]
[ValidateNotNullOrEmpty]
public string[] Name { get; set; }
/// <summary>
/// Specifies the version or version range of the package to be saved
/// </summary>
[SupportsWildcards]
[Parameter(ParameterSetName = AsNupkgParameterSet, ValueFromPipelineByPropertyName = true)]
[Parameter(ParameterSetName = IncludeXmlParameterSet, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string Version { get; set; }
/// <summary>
/// Specifies to allow saving of prerelease versions
/// </summary>
[Parameter(ParameterSetName = AsNupkgParameterSet, ValueFromPipelineByPropertyName = true)]
[Parameter(ParameterSetName = IncludeXmlParameterSet, ValueFromPipelineByPropertyName = true)]
[Alias("IsPrerelease")]
public SwitchParameter Prerelease { get; set; }
/// <summary>
/// Specifies the specific repositories to search within.
/// </summary>
[SupportsWildcards]
[Parameter(ValueFromPipelineByPropertyName = true)]
[ArgumentCompleter(typeof(RepositoryNameCompleter))]
[ValidateNotNullOrEmpty]
public string[] Repository { get; set; }
/// <summary>
/// Specifies a user account that has rights to save a resource from a specific repository.
/// </summary>
[Parameter]
public PSCredential Credential { get; set; }
/// <summary>
/// Saves the resource as a .nupkg
/// </summary>
[Parameter(ParameterSetName = AsNupkgParameterSet)]
[Parameter(ParameterSetName = InputObjectParameterSet)]
public SwitchParameter AsNupkg { get; set; }
/// <summary>
/// Saves the metadata XML file with the resource
/// </summary>
[Parameter(ParameterSetName = IncludeXmlParameterSet)]
[Parameter(ParameterSetName = InputObjectParameterSet)]
public SwitchParameter IncludeXml { get; set; }
/// <summary>
/// The destination where the resource is to be installed. Works for all resource types.
/// </summary>
[Parameter(HelpMessage = "Path to save the package to.")]
[ValidateNotNullOrEmpty]
public string Path
{
get
{ return _path; }
set
{
if (WildcardPattern.ContainsWildcardCharacters(value))
{
throw new PSArgumentException("Wildcard characters are not allowed in the path.");
}
// This will throw if path cannot be resolved
_path = GetResolvedProviderPathFromPSPath(value, out ProviderInfo provider).First();
}
}
private string _path;
/// <summary>
/// The destination where the resource is to be temporarily saved to.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string TemporaryPath
{
get
{ return _tmpPath; }
set
{
if (WildcardPattern.ContainsWildcardCharacters(value))
{
throw new PSArgumentException("Wildcard characters are not allowed in the temporary path.");
}
// This will throw if path cannot be resolved
_tmpPath = GetResolvedProviderPathFromPSPath(value, out ProviderInfo provider).First();
}
}
private string _tmpPath;
/// <summary>
/// Suppresses being prompted for untrusted sources.
/// </summary>
[Parameter]
public SwitchParameter TrustRepository { get; set; }
/// <summary>
/// Passes the resource saved to the console.
/// </summary>
[Parameter]
public SwitchParameter PassThru { get; set; }
/// <summary>
/// Used for pipeline input.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = InputObjectParameterSet, HelpMessage = "PSResourceInfo object representing the package to save.")]
[ValidateNotNullOrEmpty]
[Alias("ParentResource")]
public PSResourceInfo[] InputObject { get; set; }
/// <summary>
/// Skips the check for resource dependencies, so that only found resources are saved,
/// and not any resources the found resource depends on.
/// </summary>
[Parameter]
public SwitchParameter SkipDependencyCheck { get; set; }
/// <summary>
/// Check validation for signed and catalog files
/// </summary>
[Parameter]
public SwitchParameter AuthenticodeCheck { get; set; }
/// <summary>
/// Suppresses progress information.
/// </summary>
[Parameter]
public SwitchParameter Quiet { get; set; }
/// <summary>
/// For modules that require a license, AcceptLicense automatically accepts the license agreement during installation.
/// </summary>
[Parameter]
public SwitchParameter AcceptLicense { get; set; }
#endregion
#region Method overrides
protected override void BeginProcessing()
{
// Create a repository story (the PSResourceRepository.xml file) if it does not already exist
// This is to create a better experience for those who have just installed v3 and want to get up and running quickly
RepositorySettings.CheckRepositoryStore();
var networkCred = Credential != null ? new NetworkCredential(Credential.UserName, Credential.Password) : null;
// If path is not provided, use current path.
if (string.IsNullOrEmpty(_path))
{
_path = GetResolvedProviderPathFromPSPath(SessionState.Path.CurrentFileSystemLocation.Path, out ProviderInfo provider).First();
WriteVerbose($"No path was provided. Using the current working directory '{_path}.'");
}
_installHelper = new InstallHelper(cmdletPassedIn: this, networkCredential: networkCred);
}
protected override void ProcessRecord()
{
switch (ParameterSetName)
{
case AsNupkgParameterSet:
case IncludeXmlParameterSet:
ProcessSaveHelper(
pkgNames: Name,
pkgVersion: Version,
pkgPrerelease: Prerelease,
pkgRepository: Repository);
break;
case InputObjectParameterSet:
foreach (var inputObj in InputObject)
{
string normalizedVersionString = Utils.GetNormalizedVersionString(inputObj.Version.ToString(), inputObj.Prerelease);
ProcessSaveHelper(
pkgNames: new string[] { inputObj.Name },
pkgVersion: normalizedVersionString,
pkgPrerelease: inputObj.IsPrerelease,
pkgRepository: new string[] { inputObj.Repository });
}
break;
default:
Dbg.Assert(false, "Invalid parameter set");
break;
}
}
#endregion
#region Private methods
private void ProcessSaveHelper(string[] pkgNames, string pkgVersion, bool pkgPrerelease, string[] pkgRepository)
{
WriteDebug("In SavePSResource::ProcessSaveHelper()");
var namesToSave = Utils.ProcessNameWildcards(pkgNames, removeWildcardEntries: false, out string[] errorMsgs, out bool nameContainsWildcard);
if (nameContainsWildcard)
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Name with wildcards is not supported for Save-PSResource cmdlet"),
"NameContainsWildcard",
ErrorCategory.InvalidArgument,
this));
return;
}
foreach (string error in errorMsgs)
{
WriteError(new ErrorRecord(
new PSInvalidOperationException(error),
"ErrorFilteringNamesForUnsupportedWildcards",
ErrorCategory.InvalidArgument,
this));
}
// this catches the case where Name wasn't passed in as null or empty,
// but after filtering out unsupported wildcard names there are no elements left in namesToSave
if (namesToSave.Length == 0)
{
WriteDebug("Name was not provided or could not be resolved");
return;
}
// parse Version
if (!Utils.TryGetVersionType(
version: pkgVersion,
nugetVersion: out NuGetVersion nugetVersion,
versionRange: out VersionRange versionRange,
versionType: out VersionType versionType,
out string versionParseError))
{
ThrowTerminatingError(new ErrorRecord(
new ArgumentException(versionParseError),
"IncorrectVersionFormat",
ErrorCategory.InvalidArgument,
this));
}
// figure out if version is a prerelease or not.
// if condition is not met, prerelease is the value passed in via the parameter.
if (!string.IsNullOrEmpty(pkgVersion) && pkgVersion.Contains('-'))
{
pkgPrerelease = true;
}
var installedPkgs = _installHelper.BeginInstallPackages(
names: namesToSave,
versionRange: versionRange,
nugetVersion: nugetVersion,
versionType: versionType,
versionString: pkgVersion,
prerelease: pkgPrerelease,
repository: pkgRepository,
acceptLicense: AcceptLicense,
quiet: Quiet,
reinstall: true,
force: false,
trustRepository: TrustRepository,
noClobber: false,
asNupkg: AsNupkg,
includeXml: IncludeXml,
skipDependencyCheck: SkipDependencyCheck,
authenticodeCheck: AuthenticodeCheck,
savePkg: true,
pathsToInstallPkg: new List<string> { _path },
scope: null,
tmpPath: _tmpPath,
pkgsInstalled: new HashSet<string>(StringComparer.InvariantCultureIgnoreCase));
if (PassThru)
{
foreach (PSResourceInfo pkg in installedPkgs)
{
WriteObject(pkg);
}
}
}
#endregion
}
}