-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathRegisterPSResourceRepository.cs
More file actions
478 lines (413 loc) · 19.8 KB
/
RegisterPSResourceRepository.cs
File metadata and controls
478 lines (413 loc) · 19.8 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.PowerShell.PSResourceGet.UtilClasses;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Dbg = System.Diagnostics.Debug;
namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
{
/// <summary>
/// The Register-PSResourceRepository cmdlet replaces the Register-PSRepository from V2.
/// It registers a repository for PowerShell modules.
/// The repository is registered to the current user's scope and does not have a system-wide scope.
/// </summary>
[Cmdlet(VerbsLifecycle.Register,
"PSResourceRepository",
DefaultParameterSetName = NameParameterSet,
SupportsShouldProcess = true,
ConfirmImpact = ConfirmImpact.Low)]
public sealed
class RegisterPSResourceRepository : PSCmdlet, IDynamicParameters
{
#region Members
private readonly string PSGalleryRepoName = "PSGallery";
private readonly string PSGalleryRepoUri = "https://www.powershellgallery.com/api/v2";
private const int DefaultPriority = 50;
private const bool DefaultTrusted = false;
private const string NameParameterSet = "NameParameterSet";
private const string PSGalleryParameterSet = "PSGalleryParameterSet";
private const string RepositoriesParameterSet = "RepositoriesParameterSet";
private Uri _uri;
private CredentialProviderDynamicParameters _credentialProvider;
#endregion
#region Parameters
/// <summary>
/// Specifies name for the repository to be registered.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = NameParameterSet, HelpMessage = "Name of the repository that is to be registered.")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// Specifies the location of the repository to be registered.
/// </summary>
[Parameter(Mandatory = true, Position = 1, ParameterSetName = NameParameterSet, HelpMessage = "Location of the repository that is to be registered.")]
[ValidateNotNullOrEmpty]
public string Uri { get; set; }
/// <summary>
/// When specified, registers PSGallery repository.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = PSGalleryParameterSet, HelpMessage = "PSGallery switch used to indicate registering PSGallery repository.")]
public SwitchParameter PSGallery { get; set; }
/// <summary>
/// Specifies a hashtable of repositories and is used to register multiple repositories at once.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = RepositoriesParameterSet, HelpMessage = "Hashtable including information on single or multiple repositories to be registered.")]
[ValidateNotNullOrEmpty]
public Hashtable[] Repository {get; set;}
/// <summary>
/// Specifies whether the repository should be trusted.
/// </summary>
[Parameter(ParameterSetName = NameParameterSet)]
[Parameter(ParameterSetName = PSGalleryParameterSet)]
public SwitchParameter Trusted { get; set; }
/// <summary>
/// Specifies the priority ranking of the repository, such that repositories with higher ranking priority are searched
/// before a lower ranking priority one, when searching for a repository item across multiple registered repositories.
/// Valid priority values range from 0 to 100, such that a lower numeric value (i.e 10) corresponds
/// to a higher priority ranking than a higher numeric value (i.e 40). Has default value of 50.
/// </summary>
[Parameter(ParameterSetName = NameParameterSet)]
[Parameter(ParameterSetName = PSGalleryParameterSet)]
[ValidateRange(0, 100)]
public int Priority { get; set; } = DefaultPriority;
/// <summary>
/// Specifies the Api version of the repository to be set.
/// </summary>
[Parameter(ParameterSetName = NameParameterSet)]
[ValidateSet("V2", "V3", "Local", "NugetServer", "ContainerRegistry")]
public PSRepositoryInfo.APIVersion ApiVersion { get; set; }
/// <summary>
/// Specifies vault and secret names as PSCredentialInfo for the repository.
/// </summary>
[Parameter(ParameterSetName = NameParameterSet)]
public PSCredentialInfo CredentialInfo { get; set; }
/// <summary>
/// When specified, displays the successfully registered repository and its information.
/// </summary>
[Parameter]
public SwitchParameter PassThru { get; set; }
/// <summary>
/// When specified, will overwrite information for any existing repository with the same name.
/// </summary>
[Parameter]
public SwitchParameter Force { get; set; }
#endregion
#region DynamicParameters
public object GetDynamicParameters()
{
// Dynamic parameter '-CredentialProvider' should not appear for PSGallery or any container registry repository.
// It should also not appear when using the 'Repositories' parameter set.
if (ParameterSetName.Equals(PSGalleryParameterSet) ||
ParameterSetName.Equals(RepositoriesParameterSet) ||
PSRepositoryInfo.IsValidContainerRegistryURL(Uri))
{
return null;
}
_credentialProvider = new CredentialProviderDynamicParameters();
return _credentialProvider;
}
#endregion
#region Methods
protected override void BeginProcessing()
{
RepositorySettings.CheckRepositoryStore();
}
protected override void ProcessRecord()
{
List<PSRepositoryInfo> items = new List<PSRepositoryInfo>();
PSRepositoryInfo.APIVersion? repoApiVersion = null;
if (MyInvocation.BoundParameters.ContainsKey(nameof(ApiVersion)))
{
repoApiVersion = ApiVersion;
}
PSRepositoryInfo.CredentialProviderType? credentialProvider = _credentialProvider?.CredentialProvider;
switch (ParameterSetName)
{
case NameParameterSet:
if (!Utils.TryCreateValidUri(uriString: Uri,
cmdletPassedIn: this,
uriResult: out _uri,
errorRecord: out ErrorRecord errorRecord))
{
ThrowTerminatingError(errorRecord);
}
try
{
items.Add(RepositorySettings.AddRepository(Name, _uri, Priority, Trusted, repoApiVersion, CredentialInfo, credentialProvider, Force, this, out string errorMsg));
if (!string.IsNullOrEmpty(errorMsg))
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(errorMsg),
"ErrorInNameParameterSet",
ErrorCategory.InvalidArgument,
this));
}
}
catch (Exception e)
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorInNameParameterSet",
ErrorCategory.InvalidArgument,
this));
}
break;
case PSGalleryParameterSet:
if (PSGallery)
{
try
{
items.Add(PSGalleryParameterSetHelper(Priority, Trusted));
}
catch (Exception e)
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorInPSGalleryParameterSet",
ErrorCategory.InvalidArgument,
this));
}
}
break;
case RepositoriesParameterSet:
try
{
items = RepositoriesParameterSetHelper();
}
catch (Exception e)
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorInRepositoriesParameterSet",
ErrorCategory.InvalidArgument,
this));
}
break;
default:
Dbg.Assert(false, "Invalid parameter set");
break;
}
if (PassThru)
{
foreach (PSRepositoryInfo repo in items)
{
WriteObject(repo);
}
}
}
private PSRepositoryInfo PSGalleryParameterSetHelper(int repoPriority, bool repoTrusted)
{
WriteDebug("In RegisterPSResourceRepository::PSGalleryParameterSetHelper()");
Uri psGalleryUri = new Uri(PSGalleryRepoUri);
WriteDebug("Internal name and uri values for PSGallery are hardcoded and validated. Priority and trusted values, if passed in, also validated");
var addedRepo = RepositorySettings.AddToRepositoryStore(PSGalleryRepoName,
psGalleryUri,
repoPriority,
repoTrusted,
apiVersion: null,
repoCredentialInfo: null,
credentialProvider: null,
Force,
this,
out string errorMsg);
if (!string.IsNullOrEmpty(errorMsg))
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(errorMsg),
"RepositoryCredentialSecretManagementUnavailableModule",
ErrorCategory.ResourceUnavailable,
this));
}
return addedRepo;
}
private List<PSRepositoryInfo> RepositoriesParameterSetHelper()
{
WriteDebug("In RegisterPSResourceRepository::RepositoriesParameterSetHelper()");
List<PSRepositoryInfo> reposAddedFromHashTable = new List<PSRepositoryInfo>();
foreach (Hashtable repo in Repository)
{
if (repo.ContainsKey(PSGalleryRepoName))
{
if (repo.ContainsKey("Name") || repo.ContainsKey("Uri") || repo.ContainsKey("CredentialInfo"))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Repository hashtable cannot contain PSGallery key with -Name, -Uri and/or -CredentialInfo key value pairs"),
"NotProvideNameUriCredentialInfoForPSGalleryRepositoriesParameterSetRegistration",
ErrorCategory.InvalidArgument,
this));
continue;
}
try
{
WriteDebug("Registering PSGallery repository");
reposAddedFromHashTable.Add(PSGalleryParameterSetHelper(
repo.ContainsKey("Priority") ? (int)repo["Priority"] : DefaultPriority,
repo.ContainsKey("Trusted") ? (bool)repo["Trusted"] : DefaultTrusted));
}
catch (Exception e)
{
WriteError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorParsingIndividualRepoPSGallery",
ErrorCategory.InvalidArgument,
this));
}
}
else
{
PSRepositoryInfo parsedRepoAdded = RepoValidationHelper(repo);
if (parsedRepoAdded != null)
{
reposAddedFromHashTable.Add(parsedRepoAdded);
}
}
}
return reposAddedFromHashTable;
}
private PSRepositoryInfo RepoValidationHelper(Hashtable repo)
{
WriteDebug("In RegisterPSResourceRepository::RepoValidationHelper()");
if (!repo.ContainsKey("Name") || repo["Name"] == null || String.IsNullOrWhiteSpace(repo["Name"].ToString()))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Repository name cannot be null"),
"NullNameForRepositoriesParameterSetRegistration",
ErrorCategory.InvalidArgument,
this));
return null;
}
if (repo["Name"].ToString().Equals("PSGallery", StringComparison.OrdinalIgnoreCase))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Cannot register PSGallery with -Name parameter. Try: Register-PSResourceRepository -PSGallery"),
"PSGalleryProvidedAsNameRepoPSet",
ErrorCategory.InvalidArgument,
this));
return null;
}
if (repo["Name"].ToString().Equals("MAR", StringComparison.OrdinalIgnoreCase))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Cannot register MAR with -Name parameter. The MAR repository is automatically registered. Try: Reset-PSResourceRepository to restore default repositories."),
"MARProvidedAsNameRepoPSet",
ErrorCategory.InvalidArgument,
this));
return null;
}
if (!repo.ContainsKey("Uri") || repo["Uri"] == null || String.IsNullOrEmpty(repo["Uri"].ToString()))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Repository Uri cannot be null"),
"NullUriForRepositoriesParameterSetRegistration",
ErrorCategory.InvalidArgument,
this));
return null;
}
if (!Utils.TryCreateValidUri(uriString: repo["Uri"].ToString(),
cmdletPassedIn: this,
uriResult: out Uri repoUri,
errorRecord: out ErrorRecord errorRecord))
{
WriteError(errorRecord);
return null;
}
PSCredentialInfo repoCredentialInfo = null;
if (repo.ContainsKey("CredentialInfo") &&
!Utils.TryCreateValidPSCredentialInfo(credentialInfoCandidate: (PSObject) repo["CredentialInfo"],
cmdletPassedIn: this,
repoCredentialInfo: out repoCredentialInfo,
errorRecord: out ErrorRecord errorRecord1))
{
WriteError(errorRecord1);
return null;
}
if (repo.ContainsKey("ApiVersion") &&
(repo["ApiVersion"] == null || String.IsNullOrEmpty(repo["ApiVersion"].ToString()) ||
!(repo["ApiVersion"].ToString().Equals("Local", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("V2", StringComparison.OrdinalIgnoreCase) ||
repo["ApiVersion"].ToString().Equals("V3", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("NugetServer", StringComparison.OrdinalIgnoreCase) ||
repo["ApiVersion"].ToString().Equals("Unknown", StringComparison.OrdinalIgnoreCase))))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Repository ApiVersion must be either 'Local', 'V2', 'V3', 'NugetServer', 'ContainRegistry' or 'Unknown'"),
"IncorrectApiVersionForRepositoriesParameterSetRegistration",
ErrorCategory.InvalidArgument,
this));
return null;
}
if (repo.ContainsKey("CredentialProvider") &&
(String.IsNullOrEmpty(repo["CredentialProvider"].ToString()) ||
!(repo["CredentialProvider"].ToString().Equals("None", StringComparison.OrdinalIgnoreCase) ||
repo["CredentialProvider"].ToString().Equals("AzArtifacts", StringComparison.OrdinalIgnoreCase))))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Repository 'CredentialProvider' must be set to either 'None' or 'AzArtifacts'"),
"InvalidCredentialProviderForRepositoriesParameterSetRegistration",
ErrorCategory.InvalidArgument,
this));
return null;
}
try
{
WriteDebug($"Registering repository '{repo["Name"]}' with uri '{repoUri}'");
var addedRepo = RepositorySettings.AddRepository(repo["Name"].ToString(),
repoUri,
repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority,
repo.ContainsKey("Trusted") ? Convert.ToBoolean(repo["Trusted"].ToString()) : DefaultTrusted,
apiVersion: repo.ContainsKey("Trusted") ? (PSRepositoryInfo.APIVersion?) repo["ApiVersion"] : null,
repoCredentialInfo,
repo.ContainsKey("CredentialProvider") ? (PSRepositoryInfo.CredentialProviderType?)repo["CredentialProvider"] : null,
Force,
this,
out string errorMsg);
if (!string.IsNullOrEmpty(errorMsg))
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(errorMsg),
"RegisterRepositoryError",
ErrorCategory.ResourceUnavailable,
this));
}
return addedRepo;
}
catch (Exception e)
{
if (!(e is ArgumentException || e is PSInvalidOperationException))
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"TerminatingErrorParsingAddingIndividualRepo",
ErrorCategory.InvalidArgument,
this));
}
WriteError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorParsingIndividualRepo",
ErrorCategory.InvalidArgument,
this));
return null;
}
}
#endregion
}
public class CredentialProviderDynamicParameters
{
PSRepositoryInfo.CredentialProviderType? _credProvider = null;
/// <summary>
/// Specifies which credential provider to use.
/// </summary>
[Parameter]
public PSRepositoryInfo.CredentialProviderType? CredentialProvider {
get
{
return _credProvider;
}
set
{
_credProvider = value;
}
}
}
}