-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathPSScriptMetadata.cs
More file actions
584 lines (495 loc) · 23.2 KB
/
PSScriptMetadata.cs
File metadata and controls
584 lines (495 loc) · 23.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
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using NuGet.Versioning;
namespace Microsoft.PowerShell.PSResourceGet.UtilClasses
{
/// <summary>
/// This class contains information for a PSScriptFileInfo (representing a .ps1 file contents).
/// </summary>
public sealed class PSScriptMetadata
{
#region Properties
/// <summary>
/// the version of the script.
/// </summary>
public NuGetVersion Version { get; private set; }
/// <summary>
/// the GUID for the script.
/// </summary>
public Guid Guid { get; private set; }
/// <summary>
/// the author for the script.
/// </summary>
public string Author { get; private set; }
/// <summary>
/// the name of the company owning the script.
/// </summary>
public string CompanyName { get; private set; }
/// <summary>
/// the copyright statement for the script.
/// </summary>
public string Copyright { get; private set; }
/// <summary>
/// the tags for the script.
/// </summary>
public string[] Tags { get; private set; }
/// <summary>
/// the Uri for the license of the script.
/// </summary>
public Uri LicenseUri { get; private set; }
/// <summary>
/// the Uri for the project relating to the script.
/// </summary>
public Uri ProjectUri { get; private set; }
/// <summary>
/// the Uri for the icon relating to the script.
/// </summary>
public Uri IconUri { get; private set; }
/// <summary>
/// the list of external module dependencies for the script.
/// </summary>
public string[] ExternalModuleDependencies { get; private set; } = Utils.EmptyStrArray;
/// <summary>
/// the list of required scripts for the parent script.
/// </summary>
public string[] RequiredScripts { get; private set; } = Utils.EmptyStrArray;
/// <summary>
/// the list of external script dependencies for the script.
/// </summary>
public string[] ExternalScriptDependencies { get; private set; } = Utils.EmptyStrArray;
/// <summary>
/// the release notes relating to the script.
/// </summary>
public string ReleaseNotes { get; private set; } = String.Empty;
/// <summary>
/// The private data associated with the script.
/// </summary>
public string PrivateData { get; private set; }
#endregion
#region Constructor
/// <summary>
/// This constructor takes metadata properties and creates PSScriptMetadata instance.
/// </summary>
public PSScriptMetadata(
string version,
Guid guid,
string author,
string companyName,
string copyright,
string[] tags,
Uri licenseUri,
Uri projectUri,
Uri iconUri,
string[] externalModuleDependencies,
string[] requiredScripts,
string[] externalScriptDependencies,
string releaseNotes,
string privateData)
{
if (String.IsNullOrEmpty(author))
{
author = Environment.UserName;
}
Version = !String.IsNullOrEmpty(version) ? new NuGetVersion (version) : new NuGetVersion("1.0.0.0");
Guid = (guid == null || guid == Guid.Empty) ? Guid.NewGuid() : guid;
Author = !String.IsNullOrEmpty(author) ? author : Environment.UserName;
CompanyName = companyName;
Copyright = copyright;
Tags = tags ?? Utils.EmptyStrArray;
LicenseUri = licenseUri;
ProjectUri = projectUri;
IconUri = iconUri;
ExternalModuleDependencies = externalModuleDependencies ?? Utils.EmptyStrArray;
RequiredScripts = requiredScripts ?? Utils.EmptyStrArray;
ExternalScriptDependencies = externalScriptDependencies ?? Utils.EmptyStrArray;
ReleaseNotes = releaseNotes;
PrivateData = privateData;
}
/// <summary>
/// This constructor is called by internal cmdlet methods and creates a PSScriptFileInfo with default values
/// for the parameters. Calling a method like PSScriptMetadata.ParseContentIntoObj() would then populate those properties.
/// </summary>
internal PSScriptMetadata() {}
#endregion
#region Internal Methods
/// <summary>
/// Parses script metadata comment (passed in as its lines) into PSScriptMetadata instance's properties
/// Also validates that this metadata has required script properties.
/// </summary>
internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord[] errors, out string[] msgs)
{
msgs = Utils.EmptyStrArray;
List<string> msgsList = new List<string>();
// parse content into a hashtable
Hashtable parsedMetadata = ParseMetadataContentHelper(commentLines, out errors);
if (errors.Length != 0)
{
return false;
}
if (parsedMetadata.Count == 0)
{
errors = new ErrorRecord[]{ new ErrorRecord(
new InvalidOperationException("PowerShell script '<#PSScriptInfo .. #>' comment block contains no metadata"),
"psScriptInfoBlockMissingMetadataError",
ErrorCategory.ParserError,
null) };
return false;
}
// check parsed metadata contains required Author, Version, Guid key values
if (!ValidateParsedContent(parsedMetadata, out errors))
{
return false;
}
// now populate the object instance
string[] delimiter = new string[]{" ", ","};
Uri parsedLicenseUri = null;
if (!String.IsNullOrEmpty((string) parsedMetadata["LICENSEURI"]))
{
if (!Uri.TryCreate((string) parsedMetadata["LICENSEURI"], UriKind.Absolute, out parsedLicenseUri))
{
msgsList.Add($"LicenseUri property {(string) parsedMetadata["LICENSEURI"]} could not be created as a Uri");
}
}
Uri parsedProjectUri = null;
if (!String.IsNullOrEmpty((string) parsedMetadata["PROJECTURI"]))
{
if (!Uri.TryCreate((string) parsedMetadata["PROJECTURI"], UriKind.Absolute, out parsedProjectUri))
{
msgsList.Add($"ProjectUri property {(string) parsedMetadata["PROJECTURI"]} could not be created as Uri");
}
}
Uri parsedIconUri = null;
if (!String.IsNullOrEmpty((string) parsedMetadata["ICONURI"]))
{
if (!Uri.TryCreate((string) parsedMetadata["ICONURI"], UriKind.Absolute, out parsedIconUri))
{
msgsList.Add($"IconUri property {(string) parsedMetadata["ICONURI"]} could not be created as Uri");
}
}
// now populate PSScriptMetadata object properties with parsed metadata
Author = (string) parsedMetadata["AUTHOR"];
Version = new NuGetVersion((string) parsedMetadata["VERSION"]);
Guid = new Guid((string) parsedMetadata["GUID"]);
CompanyName = (string) parsedMetadata["COMPANYNAME"] ?? String.Empty;
Copyright = (string) parsedMetadata["COPYRIGHT"] ?? String.Empty;
LicenseUri = parsedLicenseUri;
ProjectUri = parsedProjectUri;
IconUri = parsedIconUri;
Tags = Utils.GetStringArrayFromString(delimiter, (string) parsedMetadata["TAGS"]);;
ExternalModuleDependencies = Utils.GetStringArrayFromString(delimiter, (string) parsedMetadata["EXTERNALMODULEDEPENDENCIES"]);
RequiredScripts = Utils.GetStringArrayFromString(delimiter, (string) parsedMetadata["REQUIREDSCRIPTS"]);
ExternalScriptDependencies = Utils.GetStringArrayFromString(delimiter, (string) parsedMetadata["EXTERNALSCRIPTDEPENDENCIES"]);
ReleaseNotes = (string) parsedMetadata["RELEASENOTES"] ?? String.Empty;
PrivateData = (string) parsedMetadata["PRIVATEDATA"] ?? String.Empty;
msgs = msgsList.ToArray();
return true;
}
/// <summary>
/// Parses metadata out of PSScriptCommentInfo comment block's lines (which are passed in) into a hashtable.
/// This comment block cannot have duplicate keys.
/// </summary>
public static Hashtable ParseMetadataContentHelper(string[] commentLines, out ErrorRecord[] errors)
{
/**
Comment lines can look like this:
.KEY1 value,
.KEY2 value
.KEY3
value
.KEY4 value
value continued
*/
errors = Array.Empty<ErrorRecord>();
List<ErrorRecord> errorsList = new List<ErrorRecord>();
Hashtable parsedHelpMetadata = new Hashtable(StringComparer.OrdinalIgnoreCase);
char[] delimiter = new char[]{' ', ','};
string keyName = "";
string value = "";
for (int i = 0; i < commentLines.Length; i++)
{
string line = commentLines[i];
// scenario where line is: .KEY VALUE
// this line contains a new metadata property.
if (line.Trim().StartsWith("."))
{
// check if keyName was previously populated, if so add this key value pair to the metadata hashtable
if (!String.IsNullOrEmpty(keyName))
{
if (parsedHelpMetadata.ContainsKey(keyName))
{
errorsList.Add(new ErrorRecord(
new InvalidOperationException("PowerShell script '<#PSScriptInfo .. #>' comment block metadata cannot contain duplicate key i.e .KEY"),
"psScriptInfoDuplicateKeyError",
ErrorCategory.ParserError,
null));
continue;
}
parsedHelpMetadata.Add(keyName, value);
}
// setting count to 2 will get 1st separated string (key) into part[0] and the rest (value) into part[1] if any
string[] parts = line.Trim().TrimStart('.').Split(separator: delimiter, count: 2);
keyName = parts[0];
value = parts.Length == 2 ? parts[1] : String.Empty;
}
else if (line.Trim().StartsWith("#>"))
{
// This line signifies end of comment block, so add last recorded key value pair before the comment block ends.
if (!String.IsNullOrEmpty(keyName) && !parsedHelpMetadata.ContainsKey(keyName))
{
// only add this key value if it hasn't already been added
parsedHelpMetadata.Add(keyName, value);
}
}
else if (!String.IsNullOrEmpty(line))
{
// scenario where line contains text that is a continuation of value from previously recorded key
// this line does not starting with .KEY, and is also not an empty line.
if (value.Equals(String.Empty))
{
value += line;
}
else
{
value += Environment.NewLine + line;
}
}
}
errors = errorsList.ToArray();
return parsedHelpMetadata;
}
/// <summary>
/// Validates parsed metadata content from the hashtable to ensure required metadata (Author, Version, Guid) is present
/// and does not contain empty values.
/// </summary>
internal bool ValidateParsedContent(Hashtable parsedMetadata, out ErrorRecord[] errors)
{
List<ErrorRecord> errorsList = new List<ErrorRecord>();
if (!parsedMetadata.ContainsKey("VERSION") || String.IsNullOrEmpty((string) parsedMetadata["VERSION"]) || String.Equals(((string) parsedMetadata["VERSION"]).Trim(), String.Empty))
{
errorsList.Add(new ErrorRecord(
new ArgumentException("PSScript file is missing the required Version property"),
"psScriptMissingVersion",
ErrorCategory.ParserError,
null));
}
if (!parsedMetadata.ContainsKey("AUTHOR") || String.IsNullOrEmpty((string) parsedMetadata["AUTHOR"]) || String.Equals(((string) parsedMetadata["AUTHOR"]).Trim(), String.Empty))
{
errorsList.Add(new ErrorRecord(
new ArgumentException("PSScript file is missing the required Author property"),
"psScriptMissingAuthor",
ErrorCategory.ParserError,
null));
}
if (!parsedMetadata.ContainsKey("GUID") || String.IsNullOrEmpty((string) parsedMetadata["GUID"]) || String.Equals(((string) parsedMetadata["GUID"]).Trim(), String.Empty))
{
errorsList.Add(new ErrorRecord(
new ArgumentException("PSScript file is missing the required Guid property"),
"psScriptMissingGuid",
ErrorCategory.ParserError,
null));
}
errors = errorsList.ToArray();
return errors.Length == 0;
}
/// <summary>
/// Validates metadata properties are valid and contains required script properties
/// i.e Author, Version, Guid.
/// </summary>
internal bool ValidateContent(out ErrorRecord[] errors)
{
bool validPSScriptInfo = true;
List<ErrorRecord> errorsList = new List<ErrorRecord>();
if (Version == null || String.IsNullOrEmpty(Version.ToString()))
{
errorsList.Add(new ErrorRecord(
new ArgumentException("PSScript file is missing the required Version property"),
"psScriptMissingVersion",
ErrorCategory.ParserError,
null));
validPSScriptInfo = false;
}
if (String.IsNullOrEmpty(Author))
{
errorsList.Add(new ErrorRecord(
new ArgumentException("PSScript file is missing the required Author property"),
"psScriptMissingAuthor",
ErrorCategory.ParserError,
null));
validPSScriptInfo = false;
}
if (Guid == Guid.Empty)
{
errorsList.Add(new ErrorRecord(
new ArgumentException("PSScript file is missing the required Guid property"),
"psScriptMissingGuid",
ErrorCategory.ParserError,
null));
validPSScriptInfo = false;
}
errors = errorsList.ToArray();
return validPSScriptInfo;
}
/// <summary>
/// Emits string representation of '<#PSScriptInfo ... #>' comment and its metadata contents.
/// </summary>
internal string[] EmitContent()
{
/**
PSScriptInfo comment will be in following format:
<#PSScriptInfo
.VERSION 1.0
.GUID 544238e3-1751-4065-9227-be105ff11636
.AUTHOR manikb
.COMPANYNAME Microsoft Corporation
.COPYRIGHT (c) 2015 Microsoft Corporation. All rights reserved.
.TAGS Tag1 Tag2 Tag3
.LICENSEURI https://contoso.com/License
.PROJECTURI https://contoso.com/
.ICONURI https://contoso.com/Icon
.EXTERNALMODULEDEPENDENCIES ExternalModule1
.REQUIREDSCRIPTS Start-WFContosoServer,Stop-ContosoServerScript
.EXTERNALSCRIPTDEPENDENCIES Stop-ContosoServerScript
.RELEASENOTES
contoso script now supports following features
Feature 1
Feature 2
Feature 3
Feature 4
Feature 5
.PRIVATEDATA
#>
*/
string licenseUriString = LicenseUri == null ? String.Empty : LicenseUri.ToString();
string projectUriString = ProjectUri == null ? String.Empty : ProjectUri.ToString();
string iconUriString = IconUri == null ? String.Empty : IconUri.ToString();
string tagsString = String.Join(" ", Tags);
string externalModuleDependenciesString = String.Join(" ", ExternalModuleDependencies);
string requiredScriptsString = String.Join(" ", RequiredScripts);
string externalScriptDependenciesString = String.Join(" ", ExternalScriptDependencies);
List<string> psScriptInfoLines = new List<string>();
// Note: we add a newline to the end of each property entry in HelpInfo so that there's an empty line separating them.
psScriptInfoLines.Add($"<#PSScriptInfo{Environment.NewLine}");
psScriptInfoLines.Add($".VERSION {Version.ToString()}{Environment.NewLine}");
psScriptInfoLines.Add($".GUID {Guid.ToString()}{Environment.NewLine}");
psScriptInfoLines.Add($".AUTHOR {Author}{Environment.NewLine}");
psScriptInfoLines.Add($".COMPANYNAME {CompanyName}{Environment.NewLine}");
psScriptInfoLines.Add($".COPYRIGHT {Copyright}{Environment.NewLine}");
psScriptInfoLines.Add($".TAGS {tagsString}{Environment.NewLine}");
psScriptInfoLines.Add($".LICENSEURI {licenseUriString}{Environment.NewLine}");
psScriptInfoLines.Add($".PROJECTURI {projectUriString}{Environment.NewLine}");
psScriptInfoLines.Add($".ICONURI {iconUriString}{Environment.NewLine}");
psScriptInfoLines.Add($".EXTERNALMODULEDEPENDENCIES {externalModuleDependenciesString}{Environment.NewLine}");
psScriptInfoLines.Add($".REQUIREDSCRIPTS {requiredScriptsString}{Environment.NewLine}");
psScriptInfoLines.Add($".EXTERNALSCRIPTDEPENDENCIES {externalScriptDependenciesString}{Environment.NewLine}");
psScriptInfoLines.Add($".RELEASENOTES{Environment.NewLine}{ReleaseNotes}{Environment.NewLine}");
psScriptInfoLines.Add($".PRIVATEDATA{Environment.NewLine}{PrivateData}{Environment.NewLine}");
psScriptInfoLines.Add("#>");
return psScriptInfoLines.ToArray();
}
/// <summary>
/// Updates contents of the script metadata properties from any (non-default) values passed in.
/// </summary>
internal bool UpdateContent(
string version,
Guid guid,
string author,
string companyName,
string copyright,
string[] tags,
Uri licenseUri,
Uri projectUri,
Uri iconUri,
string[] externalModuleDependencies,
string[] requiredScripts,
string[] externalScriptDependencies,
string releaseNotes,
string privateData,
out ErrorRecord error)
{
error = null;
if (!String.IsNullOrEmpty(version))
{
if (!NuGetVersion.TryParse(version, out NuGetVersion updatedVersion))
{
error = new ErrorRecord(
new ArgumentException("Version provided for update could not be parsed successfully into NuGetVersion"),
"VersionParseIntoNuGetVersion",
ErrorCategory.ParserError,
null);
return false;
}
Version = updatedVersion;
}
if (guid != Guid.Empty)
{
Guid = guid;
}
if (!String.IsNullOrEmpty(author))
{
Author = author;
}
if (!String.IsNullOrEmpty(companyName)){
CompanyName = companyName;
}
if (!String.IsNullOrEmpty(copyright)){
Copyright = copyright;
}
if (tags != null && tags.Length != 0){
Tags = tags;
}
if (licenseUri != null && !licenseUri.Equals(default(Uri))){
LicenseUri = licenseUri;
}
if (projectUri != null && !projectUri.Equals(default(Uri))){
ProjectUri = projectUri;
}
if (iconUri != null && !iconUri.Equals(default(Uri))){
IconUri = iconUri;
}
if (externalModuleDependencies != null && externalModuleDependencies.Length != 0){
ExternalModuleDependencies = externalModuleDependencies;
}
if (requiredScripts != null && requiredScripts.Length != 0)
{
RequiredScripts = requiredScripts;
}
if (externalScriptDependencies != null && externalScriptDependencies.Length != 0){
ExternalScriptDependencies = externalScriptDependencies;
}
if (!String.IsNullOrEmpty(releaseNotes))
{
ReleaseNotes = releaseNotes;
}
if (!String.IsNullOrEmpty(privateData))
{
PrivateData = privateData;
}
return true;
}
internal Hashtable ToHashtable()
{
// Constructor would be called first, which handles empty null values for required properties.
Hashtable metadataHashtable = new Hashtable(StringComparer.OrdinalIgnoreCase);
metadataHashtable.Add(nameof(Version), Version);
metadataHashtable.Add(nameof(Guid), Guid);
metadataHashtable.Add(nameof(Author), Author);
metadataHashtable.Add(nameof(CompanyName), CompanyName);
metadataHashtable.Add(nameof(Copyright), Copyright);
metadataHashtable.Add(nameof(Tags), Tags);
metadataHashtable.Add(nameof(LicenseUri), LicenseUri);
metadataHashtable.Add(nameof(ProjectUri), ProjectUri);
metadataHashtable.Add(nameof(IconUri), IconUri);
metadataHashtable.Add(nameof(ExternalModuleDependencies), ExternalModuleDependencies);
metadataHashtable.Add(nameof(RequiredScripts), RequiredScripts);
metadataHashtable.Add(nameof(ExternalScriptDependencies), ExternalScriptDependencies);
metadataHashtable.Add(nameof(ReleaseNotes), ReleaseNotes);
metadataHashtable.Add(nameof(PrivateData), PrivateData);
return metadataHashtable;
}
#endregion
}
}