-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathSetPSResourceRepository.cs
More file actions
356 lines (307 loc) · 13.6 KB
/
SetPSResourceRepository.cs
File metadata and controls
356 lines (307 loc) · 13.6 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
// 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 Set-PSResourceRepository cmdlet is used to set information for a repository.
/// </summary>
[Cmdlet(VerbsCommon.Set,
"PSResourceRepository",
DefaultParameterSetName = NameParameterSet,
SupportsShouldProcess = true)]
public sealed class SetPSResourceRepository : PSCmdlet, IDynamicParameters
{
#region Members
private const string NameParameterSet = "NameParameterSet";
private const string RepositoriesParameterSet = "RepositoriesParameterSet";
private const int DefaultPriority = -1;
private Uri _uri;
private CredentialProviderDynamicParameters _credentialProvider;
#endregion
#region Parameters
/// <summary>
/// Specifies the name of the repository to be set.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = NameParameterSet, HelpMessage = "Name of the repository to set properties for.")]
[ArgumentCompleter(typeof(RepositoryNameCompleter))]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// Specifies the location of the repository to be set.
/// </summary>
[Parameter(ParameterSetName = NameParameterSet)]
[ValidateNotNullOrEmpty]
public string Uri { 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 set specified information for.")]
[ValidateNotNullOrEmpty]
public Hashtable[] Repository { get; set; }
/// <summary>
/// Specifies whether the repository should be trusted.
/// </summary>
[Parameter(ParameterSetName = NameParameterSet)]
public SwitchParameter Trusted
{
get
{ return _trusted; }
set
{
_trusted = value;
isSet = true;
}
}
private SwitchParameter _trusted;
private bool isSet;
/// <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).
/// </summary>
[Parameter(ParameterSetName = NameParameterSet)]
[ValidateNotNullOrEmpty]
[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; }
#endregion
#region DynamicParameters
public object GetDynamicParameters()
{
PSRepositoryInfo repository = RepositorySettings.Read(new[] { Name }, out string[] _).FirstOrDefault();
// Dynamic parameter '-CredentialProvider' should not appear for PSGallery, MAR, or any container registry repository.
// It should also not appear when using the 'Repositories' parameter set.
if (repository is not null &&
(repository.Name.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) ||
repository.Name.Equals("MAR", StringComparison.OrdinalIgnoreCase) ||
ParameterSetName.Equals(RepositoriesParameterSet) ||
repository.IsContainerRegistry()))
{
return null;
}
_credentialProvider = new CredentialProviderDynamicParameters();
return _credentialProvider;
}
#endregion
#region Private methods
protected override void BeginProcessing()
{
RepositorySettings.CheckRepositoryStore();
}
protected override void ProcessRecord()
{
// determine if either 1 of 5 values are attempting to be set: Uri, Priority, Trusted, APIVersion, CredentialInfo.
// if none are (i.e only Name parameter was provided, write error)
if (ParameterSetName.Equals(NameParameterSet) &&
!MyInvocation.BoundParameters.ContainsKey(nameof(Uri)) &&
!MyInvocation.BoundParameters.ContainsKey(nameof(Priority)) &&
!MyInvocation.BoundParameters.ContainsKey(nameof(Trusted)) &&
!MyInvocation.BoundParameters.ContainsKey(nameof(ApiVersion)) &&
!MyInvocation.BoundParameters.ContainsKey(nameof(CredentialInfo)) &&
!MyInvocation.BoundParameters.ContainsKey(nameof(CredentialProvider)))
{
ThrowTerminatingError(new ErrorRecord(
new ArgumentException("Must set Uri, Priority, Trusted, ApiVersion, CredentialInfo, or CredentialProvider parameter"),
"SetRepositoryParameterBindingFailure",
ErrorCategory.InvalidArgument,
this));
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(Uri)))
{
if (!Utils.TryCreateValidUri(Uri, this, out _uri, out ErrorRecord errorRecord))
{
ThrowTerminatingError(errorRecord);
}
}
PSRepositoryInfo.APIVersion? repoApiVersion = null;
if (MyInvocation.BoundParameters.ContainsKey(nameof(ApiVersion)))
{
repoApiVersion = ApiVersion;
}
PSRepositoryInfo.CredentialProviderType? credentialProvider = _credentialProvider?.CredentialProvider;
List<PSRepositoryInfo> items = new List<PSRepositoryInfo>();
switch(ParameterSetName)
{
case NameParameterSet:
try
{
items.Add(RepositorySettings.UpdateRepositoryStore(Name,
_uri,
Priority,
Trusted,
isSet,
DefaultPriority,
repoApiVersion,
CredentialInfo,
credentialProvider,
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 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 item in items)
{
WriteObject(item);
}
}
}
private List<PSRepositoryInfo> RepositoriesParameterSetHelper()
{
WriteDebug("In SetPSResourceRepository::RepositoriesParameterSetHelper()");
List<PSRepositoryInfo> reposUpdatedFromHashtable = new List<PSRepositoryInfo>();
foreach (Hashtable repo in Repository)
{
if (!repo.ContainsKey("Name") || repo["Name"] == null || String.IsNullOrEmpty(repo["Name"].ToString()))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Repository hashtable must contain Name key value pair"),
"NullNameForRepositoriesParameterSetRepo",
ErrorCategory.InvalidArgument,
this));
continue;
}
PSRepositoryInfo parsedRepoAdded = RepoValidationHelper(repo);
if (parsedRepoAdded != null)
{
reposUpdatedFromHashtable.Add(parsedRepoAdded);
}
}
return reposUpdatedFromHashtable;
}
private PSRepositoryInfo RepoValidationHelper(Hashtable repo)
{
WriteDebug("In SetPSResourceRepository::RepoValidationHelper()");
WriteDebug($"Parsing through repository '{repo["Name"]}'");
Uri repoUri = null;
if (repo.ContainsKey("Uri"))
{
if (String.IsNullOrEmpty(repo["Uri"].ToString()))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Repository Uri cannot be null if provided"),
"NullUriForRepositoriesParameterSetUpdate",
ErrorCategory.InvalidArgument,
this));
return null;
}
if (!Utils.TryCreateValidUri(uriString: repo["Uri"].ToString(),
cmdletPassedIn: this,
uriResult: out repoUri,
errorRecord: out ErrorRecord errorRecord))
{
WriteError(errorRecord);
return null;
}
}
bool repoTrusted = false;
isSet = false;
if (repo.ContainsKey("Trusted"))
{
repoTrusted = (bool) repo["Trusted"];
isSet = true;
}
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;
}
PSRepositoryInfo.CredentialProviderType? credentialProvider = _credentialProvider?.CredentialProvider;
try
{
var updatedRepo = RepositorySettings.UpdateRepositoryStore(repo["Name"].ToString(),
repoUri,
repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority,
repoTrusted,
isSet,
DefaultPriority,
ApiVersion,
repoCredentialInfo,
credentialProvider,
this,
out string errorMsg);
if (!string.IsNullOrEmpty(errorMsg))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException(errorMsg),
"ErrorSettingRepository",
ErrorCategory.InvalidData,
this));
}
return updatedRepo;
}
catch (Exception e)
{
WriteError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorSettingIndividualRepoFromRepositories",
ErrorCategory.InvalidArgument,
this));
return null;
}
}
#endregion
}
}