-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathUpdatePSScriptFileInfo.cs
More file actions
326 lines (284 loc) · 11.2 KB
/
UpdatePSScriptFileInfo.cs
File metadata and controls
326 lines (284 loc) · 11.2 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.IO;
using System.Management.Automation;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.PSResourceGet.UtilClasses;
namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
{
/// <summary>
/// Updates a .ps1 file with specified properties.
/// </summary>
[Cmdlet(VerbsData.Update, "PSScriptFileInfo")]
public sealed class UpdatePSScriptFileInfo : PSCmdlet
{
#region Parameters
/// <summary>
/// The author of the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string Author { get; set; }
/// <summary>
/// The name of the company owning the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string CompanyName { get; set; }
/// <summary>
/// The copyright statement for the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string Copyright { get; set; }
/// <summary>
/// The description of the script.
/// </summary>
[Parameter()]
[ValidateNotNullOrEmpty()]
public string Description { get; set; }
/// <summary>
/// The list of external module dependencies taken by this script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string[] ExternalModuleDependencies { get; set; }
/// <summary>
/// The list of external script dependencies taken by this script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string[] ExternalScriptDependencies { get; set; }
/// <summary>
/// The unique identifier for the script. The GUID can be used to distinguish among scripts with the same name.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public Guid Guid { get; set; }
/// <summary>
/// The Uri for the icon associated with the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string IconUri { get; set; }
/// <summary>
/// The Uri for the license associated with the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string LicenseUri { get; set; }
/// <summary>
/// The path the .ps1 script info file will be created at.
/// </summary>
[Parameter(Position = 0, Mandatory = true, HelpMessage = "Path (including file name) to the script file (.ps1 file) to update.")]
[ValidateNotNullOrEmpty]
public string Path { get; set; }
/// <summary>
/// The private data associated with the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string PrivateData { get; set; }
/// <summary>
/// The Uri for the project associated with the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string ProjectUri { get; set; }
/// <summary>
/// The release notes for the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string ReleaseNotes { get; set; }
/// <summary>
/// Remove signature from signed .ps1 (if present) thereby allowing update of script to happen
/// User should re-sign the updated script afterwards.
/// </summary>
[Parameter]
public SwitchParameter RemoveSignature { get; set; }
/// <summary>
/// The list of modules required by the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public Hashtable[] RequiredModules { get; set; }
/// <summary>
/// The list of scripts required by the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string[] RequiredScripts { get; set; }
/// <summary>
/// The tags associated with the script.
/// </summary>
[Parameter]
[Alias("Tag")]
[ValidateNotNullOrEmpty()]
public string[] Tags { get; set; }
/// <summary>
/// The version of the script.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty()]
public string Version { get; set; }
#endregion
#region Methods
protected override void EndProcessing()
{
Uri projectUri = null;
if (!String.IsNullOrEmpty(ProjectUri) && !Utils.TryCreateValidUri(uriString: ProjectUri,
cmdletPassedIn: this,
uriResult: out projectUri,
errorRecord: out ErrorRecord projectErrorRecord))
{
ThrowTerminatingError(projectErrorRecord);
}
Uri licenseUri = null;
if (!String.IsNullOrEmpty(LicenseUri) && !Utils.TryCreateValidUri(uriString: LicenseUri,
cmdletPassedIn: this,
uriResult: out licenseUri,
errorRecord: out ErrorRecord licenseErrorRecord))
{
ThrowTerminatingError(licenseErrorRecord);
}
Uri iconUri = null;
if (!String.IsNullOrEmpty(IconUri) && !Utils.TryCreateValidUri(uriString: IconUri,
cmdletPassedIn: this,
uriResult: out iconUri,
errorRecord: out ErrorRecord iconErrorRecord))
{
ThrowTerminatingError(iconErrorRecord);
}
if (!Path.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
{
ThrowTerminatingError(new ErrorRecord(
new ArgumentException("File path needs to end with a .ps1 extension. Example: C:/Users/john/x/MyScript.ps1"),
"InvalidOrNonExistentPath",
ErrorCategory.InvalidArgument,
this));
}
var resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider);
if (resolvedPaths.Count != 1)
{
ThrowTerminatingError(new ErrorRecord(
new PSArgumentException("Could not resolve provided path argument into a single path."),
"InvalidPathArgumentError",
ErrorCategory.InvalidArgument,
this));
}
string resolvedPath = resolvedPaths[0];
if (!File.Exists(resolvedPath))
{
ThrowTerminatingError(new ErrorRecord(
new ArgumentException("A script file does not exist at the location specified"),
"FileDoesNotExistAtPath",
ErrorCategory.InvalidArgument,
this));
}
ModuleSpecification[] validatedRequiredModuleSpecifications = Array.Empty<ModuleSpecification>();
if (RequiredModules != null && RequiredModules.Length > 0)
{
if (!Utils.TryCreateModuleSpecification(
moduleSpecHashtables: RequiredModules,
out validatedRequiredModuleSpecifications,
out ErrorRecord[] moduleSpecErrors))
{
foreach (ErrorRecord err in moduleSpecErrors)
{
WriteError(err);
}
return;
}
}
if (!PSScriptFileInfo.TryTestPSScriptFileInfo(
scriptFileInfoPath: resolvedPath,
parsedScript: out PSScriptFileInfo parsedScriptInfo,
errors: out ErrorRecord[] errors,
out string[] verboseMsgs))
{
foreach (string msg in verboseMsgs)
{
WriteVerbose(msg);
}
foreach (ErrorRecord error in errors)
{
WriteError(error);
}
return;
}
bool signatureRemoved = false;
if (parsedScriptInfo.ScriptContent.ContainsSignature)
{
if (!RemoveSignature)
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException("Cannot update the script file because the file contains a signature block and updating will invalidate the signature. " +
"Use -RemoveSignature to remove the signature block, and then re-sign the file after it is updated."),
"ScriptToBeUpdatedContainsSignature",
ErrorCategory.InvalidOperation,
this));
}
signatureRemoved = true;
}
WriteDebug("Attempting to update script file contents");
if (!PSScriptFileInfo.TryUpdateScriptFileContents(
scriptInfo: parsedScriptInfo,
updatedPSScriptFileContents: out string[] updatedPSScriptFileContents,
errors: out ErrorRecord[] updateErrors,
version: Version,
guid: Guid,
author: Author,
companyName: CompanyName,
copyright: Copyright,
tags: Tags,
licenseUri: licenseUri,
projectUri: projectUri,
iconUri: iconUri,
requiredModules: validatedRequiredModuleSpecifications,
externalModuleDependencies: ExternalModuleDependencies,
requiredScripts: RequiredScripts,
externalScriptDependencies: ExternalScriptDependencies,
releaseNotes: ReleaseNotes,
privateData: PrivateData,
description: Description))
{
WriteWarning("Updating the specified script file failed due to the following error(s):");
foreach (ErrorRecord error in updateErrors)
{
WriteError(error);
}
return;
}
string tempScriptPath = null;
try
{
tempScriptPath = System.IO.Path.GetTempFileName();
File.WriteAllLines(tempScriptPath, updatedPSScriptFileContents);
File.Copy(tempScriptPath, resolvedPath, overwrite: true);
}
catch(Exception e)
{
WriteError(new ErrorRecord(
new PSInvalidOperationException($"Could not update .ps1 file due to: {e.Message}"),
"FileIOErrorDuringUpdate",
ErrorCategory.InvalidArgument,
this));
}
finally
{
if (tempScriptPath != null)
{
File.Delete(tempScriptPath);
}
}
if (signatureRemoved)
{
WriteWarning("Re-sign this script, as the original signature was removed during update.");
}
}
#endregion
}
}